动态创建C#类或对象 [英] Dynamically Create C# Class or Object
问题描述
我具有这种结构。
public class FirstClass
{
public List<Foo> FooList{ get; set; }
}
public class Foo{
//Ex:
//public string Name{ get; set; }
}
public List<Foo> GetFoo(){
//I'm use Firstclass like this here typeof(FirstClass);
//I want create here dynamic property for Foo class.
}
我的问题是,我想从 GetFoo()函数。同时,此函数返回列表 Foo类型。我正在研究在运行时动态添加C#属性 ,< a href = https://stackoverflow.com/questions/3862226/how-to-dynamically-create-a-class-in-c>如何在C#中动态创建类? 这些链接中的答案未引用为返回值或未引用到另一个类。我该怎么办?
And my problem is, i want create property for "Foo" class from "GetFoo()" function. Same time, this function return "List" "Foo" type. I'm research "Dynamically Add C# Properties at Runtime", "How to dynamically create a class in C#?" but the answers in these links are not referenced as return values or referenced to another class. How i can do this?
推荐答案
您可以动态创建继承了 Foo $ c的类。 $ c>,以及任何其他属性。因此,您可以将这些动态类的实例添加到
List< Foo>
中。
You can dynamically create classes, which inherits Foo
, with any additional properties. Thus you can add instances of those dynamic classes into List<Foo>
.
为此,可以生成如下所示的代码字符串:
To do so, one can generate a code string like following:
var bar1Code = @"
public class Bar1 : Foo
{
public Bar1(int value)
{
NewProperty = value;
}
public int NewProperty {get; set; }
}
";
然后使用 CSharpCodeProvider
进行编译:
var compilerResults = new CSharpCodeProvider()
.CompileAssemblyFromSource(
new CompilerParameters
{
GenerateInMemory = true,
ReferencedAssemblies =
{
"System.dll",
Assembly.GetExecutingAssembly().Location
}
},
bar1Code);
然后可以创建 Bar1
的实例,将其添加到 List< Foo>
中,例如将其强制转换为动态以访问动态属性:
Then one can create an instance of Bar1
, add it to List<Foo>
and, e.g. cast it to dynamic to access the dynamic property:
var bar1Type = compilerResults.CompiledAssembly.GetType("Bar1");
var bar2Type = compilerResults.CompiledAssembly.GetType("Bar2"); // By analogy
var firstClass = new FirstClass
{
FooList = new List<Foo>
{
(Foo)Activator.CreateInstance(bar1Type, 56),
(Foo)Activator.CreateInstance(bar2Type, ...)
}
};
var dynamicFoo = (dynamic)firstClass.FooList[0];
int i = dynamicFoo.NewProperty; // should be 56
这篇关于动态创建C#类或对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!