您可以使用以下方法手动构建您的类型TypeBuilder
:
// read property names from file
string[] propertyNames = { "MyTestProperty1", "MyTestProperty2" };
AssemblyName name = new AssemblyName("Foo");
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain
.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Bar");
TypeBuilder typeBuilder =
moduleBuilder.DefineType("MyTestClass", TypeAttributes.Public);
foreach (var propertyName in propertyNames)
{
PropertyBuilder property = typeBuilder.DefineProperty(
propertyName,
System.Reflection.PropertyAttributes.HasDefault,
typeof(string),
null);
MethodBuilder getter = typeBuilder.DefineMethod(
"get_" + propertyName,
MethodAttributes.Public | MethodAttributes.SpecialName,
typeof(string),
Type.EmptyTypes);
ILGenerator generator = getter.GetILGenerator();
// generate default value for property
generator.Emit(OpCodes.Ldstr, propertyName.Replace("Property", " "));
generator.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
}
Type type = typeBuilder.CreateType();
现在您可以使用您的类型:
object obj = Activator.CreateInstance(type);
foreach (var propertyName in propertyNames)
{
PropertyInfo pi = type.GetProperty(propertyName);
Console.WriteLine(pi.GetValue(obj));
}
dynamic testObj = obj;
Console.WriteLine(testObj.MyTestProperty2);
实际上,您可以更进一步,在一些配置文件中指定属性名称、类型和默认值。我把它留给你:)