System.Reflection.Emit 命名空间可以为您提供在运行时创建动态类所需的工具。但是,如果您以前从未使用过它,那么您尝试完成的任务可能会变得非常困难。当然,预制代码会有很大帮助,我认为在这里你可以找到很多。
但我建议你另辟蹊径。也许没有那么灵活,但肯定很有趣。涉及到DynamicObject类的使用:
public class DynamicClass : DynamicObject
{
private Dictionary<String, KeyValuePair<Type, Object>> m_Fields;
public DynamicClass(List<Field> fields)
{
m_Fields = new Dictionary<String, KeyValuePair<Type, Object>>();
fields.ForEach(x => m_Fields.Add
(
x.FieldName,
new KeyValuePair<Type, Object>(x.FieldType, null)
));
}
public override Boolean TryGetMember(GetMemberBinder binder, out Object result)
{
if (m_Fields.ContainsKey(binder.Name))
{
result = m_Fields[binder.Name].Value;
return true;
}
result = null;
return false;
}
public override Boolean TrySetMember(SetMemberBinder binder, Object value)
{
if (m_Fields.ContainsKey(binder.Name))
{
Type type = m_Fields[binder.Name].Key;
if (value.GetType() == type)
{
m_Fields[binder.Name] = new KeyValuePair<Type, Object>(type, value);
return true;
}
}
return false;
}
}
使用示例(请记住,Field 是一个小而简单的类,具有两个属性,Type FieldType 和 String FieldName,您必须自己实现):
List<Field>() fields = new List<Field>()
{
new Field("ID", typeof(Int32)),
new Field("Name", typeof(String))
};
dynamic myObj = new DynamicClass(fields);
myObj.ID = 10;
myObj.Name= "A";
Console.WriteLine(myObj.ID.ToString() + ") " + myObj.Name);