开发者

Adding new dynamic properties

we read in msdn we "Adding new dynamic properties" by using DynamicObject Class i write a following program

public class DemoDynamicObject : DynamicObject
{

}
class Program
{
    public static void Main()
    {
        dynamic dd = new DemoDynamicObject();
        dd.FirstName = "abc";开发者_StackOverflow中文版
    }
}

But when i run this program it gives runtime error :'DemoDynamicObject' does not contain a definition for 'FirstName' if we adding dynamic property by using DynamicObject Class then why it can give this error can anyone tell me reason and solution?


When using DynamicObject as your base class, you should provide specific overrides to TryGetMember and TrySetMember to keep track of the dynamic properties you are creating (based on the DynamicObject MSDN documentation):

class DemoDynamicObject: DynamicObject
{
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        string name = binder.Name;
        return dictionary.TryGetValue(name, out result);
    }

    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }
}

If you just want to have a dynamic object that you can add properties to, you can simply use an ExpandoObject instance, and skip the custom class inheriting from DynamicObject.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜