[Mono-list] DynamicObject

Daniel Lo Nigro lists at dan.cx
Fri Mar 1 13:50:43 UTC 2013


Yes, DynamicObject should work under Mono. Try this as a starting point for
what you want:

public class DynamicObjectTest : DynamicObject
{
private IList<object> _components;

 public DynamicObjectTest()
{
 Reset();
}

 private void Reset()
{
 _components = new List<object>();
}

public override bool TryGetMember(GetMemberBinder binder, out object result)
 {
_components.Add(binder.Name);

// Return the same object so we can chain calls
result = this;
 return true;
}

private string BuildUri()
{
 return "/" + string.Join("/", _components) + "/";
}

public void Get(object id)
{
 _components.Add(id);
var url = BuildUri();
 Console.WriteLine("GET to {0}", url);
Reset();
 }
}

class Program
{

static void Main(string[] args)
 {

dynamic foo = new DynamicObjectTest();

foo.objects.subtype.Get(1234);
}
}


On Sat, Feb 23, 2013 at 6:45 AM, Ben Timby <btimby at gmail.com> wrote:

> This question is partially about C# itself, and partially about the
> mono framework.
>
> I have some Python code I am trying to port to C#. Specifically, I am
> using dynamic members (attributes in Python). They are created upon
> being accessed.
>
> obj = MyClass()
> obj.dynamic_attribute_one = 1
> obj.dynamic_attribute_two = 2
>
> This is done in python using __getattr__() and __setattr__() magic
> methods. I think C# can do something similar using the DynamicObject
> and it's TryMember() method.
>
> http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx
>
> What I am actually doing is writing a REST API client, the client
> library allows the caller to do something like:
>
> client.objects.subtype.get(1234)
>
> Which results in a `GET /objects/subtype/1234/` request. This works
> very well in Python, and I am trying to emulate this in C#. The main
> requirement is that the client library does not need to know what
> endpoints exist, I want members to be "created" when accessed, not
> pre-defined in the class definition.
>
> I am unsure if DynamicObject is available under Mono, or if there is
> another way to accomplish what I am looking for.
> _______________________________________________
> Mono-list maillist  -  Mono-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ximian.com/pipermail/mono-list/attachments/20130302/3402cc49/attachment.html>


More information about the Mono-list mailing list