你可以动态地创建继承
Foo
类的类,并添加任意额外的属性。因此,你可以将这些动态类的实例添加到
List<Foo>
中。
为了做到这一点,可以生成以下代码字符串:
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>
中,并将其转换为 dynamic
来访问动态属性:
var bar1Type = compilerResults.CompiledAssembly.GetType("Bar1");
var bar2Type = compilerResults.CompiledAssembly.GetType("Bar2");
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;