所以我创建了一个继承DynamicObject的类
public class MyDynamicObject : DynamicObject{
private Dictionary<string, object> Fields = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return Fields.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Fields[binder.Name] = value;
return true;
}
}
在这里打电话给这个班级
public class Program
{
public static void Main()
{
dynamic person = new MyDynamicObject();
person.firstname = "Hello";
Console.WriteLine(person.firstname);
}
}
当然这会奏效。但我需要从像
这样的字符串数组创建属性string[] fields = new string[]{"taxid","newcol","addrs","gender"};
dynamic person = new MyDynamicObject();
foreach(var f in fields)
{
person.f = "hello";
}
所以输出将是person.taxi,person.newcol,person.addrs,person.gender
这可能吗?
答案 0 :(得分:1)
以某种方式公开Fields
字典,或(更好)一种允许按名称显式设置属性的方法。
请注意,ExpandoObject
已经执行此操作,因为它可以转换为IDictionary<string, object>
然后您
ExpandoObject eo = new ExpandoObject();
IDictionary<string, object> dict = eo;
dynamic d = eo;
dict["MyProperty"] = 42;
Console.WriteLine(d.MyProperty); // 42
如果您不能自己使用ExpandoObject
,则可以复制其方法。
答案 1 :(得分:0)
好的,基于@Jon Hanna的建议,我想出了一个符合我要求的解决方案。我创建了一个接受名称的新Add方法。以下是我使用的更新代码。
public class DynamicFormData : DynamicObject
{
private Dictionary<string, object> Fields = new Dictionary<string, object>();
public int Count { get { return Fields.Keys.Count; } }
public void Add(string name, string val = null)
{
if (!Fields.ContainsKey(name))
{
Fields.Add(name, val);
}
else
{
Fields[name] = val;
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (Fields.ContainsKey(binder.Name))
{
result = Fields[binder.Name];
return true;
}
return base.TryGetMember(binder, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (!Fields.ContainsKey(binder.Name))
{
Fields.Add(binder.Name, value);
}
else
{
Fields[binder.Name] = value;
}
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (Fields.ContainsKey(binder.Name) &&
Fields[binder.Name] is Delegate)
{
Delegate del = Fields[binder.Name] as Delegate;
result = del.DynamicInvoke(args);
return true;
}
return base.TryInvokeMember(binder, args, out result);
}
}
然后我就这样称呼它。
string[] fields = new string[]{"taxid","newcol","addrs","gender"};
dynamic formData = new DynamicFormData();
foreach(string field in fields)
{
formData.Add(field, null);
}