答案 0 :(得分:1)
Microsoft发布了一个用于创建动态linq查询的库。有一个ClassFactory可用于在运行时创建类。
以下是一个例子:
class Program
{
static void SetPropertyValue(object instance, string name, object value)
{
// this is just for example, it would be wise to cache the PropertyInfo's
instance.GetType().GetProperty(name)?.SetValue(instance, value);
}
static void Main(string[] args)
{
// create an enumerable which defines the properties
var properties = new[]
{
new DynamicProperty("Name", typeof(string)),
new DynamicProperty("Age", typeof(int)),
};
// create the class type
var myClassType = ClassFactory.Instance.GetDynamicClass(properties);
// define a List<YourClass> type.
var myListType = typeof(List<>).MakeGenericType(myClassType);
// create an instance of the list
var myList = (IList)Activator.CreateInstance(myListType);
// create an instance of an item
var first = Activator.CreateInstance(myClassType);
// use the method above to fill the properties
SetPropertyValue(first, "Name", "John");
SetPropertyValue(first, "Age", 24);
// add it to the list
myList.Add(first);
var second = Activator.CreateInstance(myClassType);
SetPropertyValue(second, "Name", "Peter");
SetPropertyValue(second, "Age", 38);
myList.Add(second);
}
}
您可以在此处下载:DynamicLibrary.cs
答案 1 :(得分:-1)
您可以使用以下命令创建班级列表:
List<ClassA> list = new List<ClassA>();
将您创建的该类的对象添加到列表中:
list.Add(dynamic);
答案 2 :(得分:-1)
如果您只是希望数据采用未定义的格式,则可以使用Dictionary
例如:
字典&lt; string,object&gt; param = new Dictionary&lt; string,object&gt;();
param.Add(&#34; msg&#34;,&#34; hello&#34;);
param.Add(&#34; number&#34;,1234);
稍后可以访问:
param [&#34; msg&#34;]为字符串
param [&#34; number&#34;] as int