C# 4.0: Dynamic, Inheriting from DynamicObject

十年热恋 提交于 2021-01-27 06:09:25

问题


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?


回答1:


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




回答2:


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;
    }
}



回答3:


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



来源:https://stackoverflow.com/questions/3874875/c-sharp-4-0-dynamic-inheriting-from-dynamicobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!