开发者

C# 4.0: Dynamic, Inheriting from DynamicObject

开发者 https://www.devze.com 2023-01-18 19:45 出处:网络
Let\'s 开发者_高级运维say I have this: dynamic foo = new Foobar(); And I have this: public class Foobar : DynamicObject

Let's 开发者_高级运维say I have this:

dynamic foo = new Foobar();

And I have this:

public class Foobar : DynamicObject
{

}

The question is, is it possible to override members of DynamicObject so that this code:

string name = new Foobar().Name

Does not throw an Exception at run-time? I want to return default for name's if Name is not a member.

Possible? What do I need to override?


Override TryGetMember (and TrySetMember). Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as getting a value for a property.

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember.aspx


Something like this:

class Foobar : DynamicObject 
{
    private object m_object;

    public ExposedObjectSimple(object obj)
    {
        m_object = obj;
    }

    public override bool TryInvokeMember(
            InvokeMemberBinder binder, object[] args, out object result)
    {
        //Trying to find appropriate property
        var property = m_object.GetType().GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
        if (property != null)
        {
            result = (string)property.GetValue(b, null);
            return true;
        }

        result = SomeDefaultName;
        return true;
    }
}


You need to override TryGetMember. Just set to always return true, and provide the default if the member does not exist.

0

精彩评论

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