自定义的DynamicObject类_.NET4.0新特性

//自定义的DynamicObject类

public class MyDynamicObject : DynamicObject
{
    private Dictionary m_Values = new Dictionary(StringComparer.OrdinalIgnoreCase);
    public MyDynamicObject()
    {
    }

 

    public void SetMember(string propertyName, object value)
    {
        if (value == DBNull.Value)
        {
            m_Values[propertyName] = null;
        }
        else
        {
            m_Values[propertyName] = value;
        }
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (m_Values.ContainsKey(binder.Name))
        {
            result = m_Values[binder.Name];
        }
        else
        {
            //throw new System.MissingMemberException("The property " + binder.Name + " does not exist.");
            result = null;
        }
        return true;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        SetMember(binder.Name, value);
        return true;
    }
}

//在程序中调用

 #region DynamicObject
        dynamic myDO = new MyDynamicObject();
        myDO.NAME="Tea";//没有定义NAME属性,却可以动态调用赋值,
        myDO.SetMember("age", 23);
        string name = myDO.NAME;
        int age = myDO.age;//不需要类型装换
 #endregion

你可能感兴趣的:(DynamicObject类,.NET4.0)