我想创建一个具有固定属性的类,并且能够将它们扩展为动态或 ExpandoObject 。 e.g:
public class DynamicInstance : DynamicObject
{
public string FixedTestProperty { get; set; }
}
用法:
DynamicInstance myCustomObj = new DynamicInstance();
myCustomObj.FixedTestProperty = "FixedTestValue";
myCustomObj.DynamicCreatedTestProperty = "Custom dynamic property value";
最后,如果我用json.net或其他类似的方法输出那个类,那么就输出类似的东西:
{
FixedTestProperty: 'FixedTestValue',
DynamicCreatedTestProperty: 'Custom dynamic property value'
}
答案 0 :(得分:1)
您需要继承DynamicObject
并覆盖TryGetMember
和TrySetMember
方法。这是一个有一个名为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。
答案 1 :(得分:-1)
可以在DynamicObject上使用TrySetMember。
底部的示例显示了如何执行此操作:https://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trysetmember(v=vs.110).aspx