您还没有发布任何代码,所以很难说,但这里有一个绝对有效的示例。这是我今天阅读的内容的修改版本。希望能帮助到你
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;
}
}
}