有什么方法可以创建与动态或 ExpandoObject 具有相同行为的 class?

There is any way to create a class with the same behavior as dynamic or ExpandoObject?

我想创建一个具有固定属性的 class 并能够像 dynamicExpandoObject 那样扩展它们。 例如:

public class DynamicInstance : DynamicObject
{
    public string FixedTestProperty { get; set; }
}

用法:

DynamicInstance myCustomObj = new DynamicInstance();

myCustomObj.FixedTestProperty = "FixedTestValue";
myCustomObj.DynamicCreatedTestProperty = "Custom dynamic property value";

最后,如果我将 class 序列化为 json.net 或其他类似的输出:

{
   FixedTestProperty: 'FixedTestValue',
   DynamicCreatedTestProperty: 'Custom dynamic property value'
}

您需要继承DynamicObject并覆盖TryGetMemberTrySetMember方法。这是一个 class,其中有一个 属性 名为 One。但是,您可以动态添加更多内容。

public class ExpandOrNot : DynamicObject
{
    public string One { get; set; }

    // The inner dictionary.
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    // This property returns the number of elements
    // in the inner dictionary.
    public int Count
    {
        get
        {
            return dictionary.Count;
        }
    }

    // If you try to get a value of a property 
    // not defined in the class, this method is called.
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        // Converting the property name to lowercase
        // so that property names become case-insensitive.
        string name = binder.Name.ToLower();

        // If the property name is found in a dictionary,
        // set the result parameter to the property value and return true.
        // Otherwise, return false.
        return dictionary.TryGetValue(name, out result);
    }

    // If you try to set a value of a property that is
    // not defined in the class, this method is called.
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        // Converting the property name to lowercase
        // so that property names become case-insensitive.
        dictionary[binder.Name.ToLower()] = value;

        // You can always add a value to a dictionary,
        // so this method always returns true.
        return true;
    }
}

用法

dynamic exp = new ExpandOrNot { One = "1" };
exp.Two = "2";

更多信息here

<== Fiddle Me ==>

这可以在 DynamicObject 上使用 TrySetMember。

底部的示例显示了如何操作:https://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trysetmember(v=vs.110).aspx