I'm experimenting with C# 4.0's dynamic object model.
I've cr开发者_JS百科eated an abstract class named "Block" that inherits from DynamicObject. It overrides TryGetMember and TrySetMember.
Furthermore I've created a usable class named "Brush" that inherits from "Block". I want it to be usable dynamically.
But when I create a dynamic object from it and try to access a runtime bound member, it pelts me with an exception telling me that the member doesn't exist. The overridden TryGetMember or TrySetMember methods of the abstract parent class aren't getting called.
Is this behaviour to be expected?
Thank you!
You haven't posted any code so its hard to tell but here is a sample which definately works. It is a modified version of stuff I was reading today. Hope it helps
namespace DynamicStuff
{
public class Program
{
static void Main(string[] args)
{
dynamic brush = new Brush();
brush.Handle = "Wooden";
brush.Colour = "Red";
Console.WriteLine(brush.Handle + " " + brush.Colour);
Console.WriteLine(
"Number of dynamic properties:" + brush.Count);
}
}
public class Brush : Block
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
Console.Out.WriteLine("About To call TryGetMember base");
object res = null;
bool retVal = base.TryGetMember(binder, out res);
result = res;
return retVal;
}
public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value)
{
Console.Out.WriteLine("About to call TrySetMember base");
return base.TrySetMember(binder, value);
}
}
public abstract class Block : DynamicObject
{
private Dictionary<string, object> d = new Dictionary<string, object>();
public int Count
{
get
{
return d.Count;
}
}
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
Console.Out.WriteLine("In TryGetMember in block");
string name = binder.Name.ToLower();
return d.TryGetValue(name, out result);
}
public override bool TrySetMember(
SetMemberBinder binder, object value)
{
Console.Out.WriteLine("In TrySetMember in block");
d[binder.Name.ToLower()] = value;
return true;
}
}
}
精彩评论