本文译自:Generating C# .NET Classes at Runtime
做者:WedPortgit
在个人C#职业生涯中,有几回我不得不在运行时生成新的类型。但愿把它写下来能帮助有相同应用需求的人。这也意味着我之后没必要在查找相同问题的StackOverflow文章了。我最初是在.NET 4.6.2中这样作的,但我已经更新到为.NET Core 3.0提供了示例。全部代码均可以在个人GitHub上面找到。
GitHub:https://github.com/cheungt6/public/tree/master/ReflectionEmitClassGenerationgithub
在运行时生产新类型的需求一般是因为运行时才知道类属性,知足性能要求以及须要在新类型中添加功能。当你尝试这样作的时候,你应该考虑的第一件事是:这是否真的是一个明智的解决方案。在深刻思考以前,还有不少其余事情能够尝试,问你本身这样的问题:数组
若是你认为这仍然是必要的,请继续阅读下面的内容。框架
做为一名开发人员,我将大量数据绑定到各类WPF Grids中。大多数时候属性是固定的,我可使用预约义的类。有时候,我不得不动态的构建网格,而且可以在应用程序运行时更改数据。采起如下显示ID和一些财务数据的类(FTSE和CAC是指数,其属性表明指数价格):ide
public class PriceHolderViewModel : ViewModelBase { public long Id { get; set; } public decimal FTSE100 { get; set; } public decimal CAC40 { get; set; } }
若是咱们仅对其中的属性感兴趣,该类定义的很是棒。可是,若是要使用更多属性扩展此类,则须要在代码中添加它,从新编译并在新版本中进行部署。性能
相反的,咱们能够作的是跟踪对象所需的属性,并在运行时构建类。这将容许咱们在须要是不断的添加和删除属性,并使用反射来更新它们的值。ui
// Keep track of my properties var _properties = new Dictionary<string, Type>(new[]{ new KeyValuePair<string, Type>( "FTSE100", typeof(Decimal) ), new KeyValuePair<string, Type>( "CAC40", typeof(Decimal) ) });
下面的示例向您展现了如何在运行时构建新类型。你须要使用**System.Reflection.Emit**
库来构造一个新的动态程序集,您的类将在其中建立,而后是模块和类型。与旧的** .NET Framework**
框架不一样,在旧的版本中,你须要在当前程序的AppDomain
中建立程序集 ,而在** .NET Core**
中,AppDomain
再也不可用。你将看到我使用GUID建立了一个新类型名称,以便于跟踪类型的版本。在之前,你不能建立具备相同名称的两个类型,可是如今彷佛不是这样了。调试
public Type GeneratedType { private set; get; } private void Initialise() { var newTypeName = Guid.NewGuid().ToString(); var assemblyName = new AssemblyName(newTypeName); var dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); var dynamicModule = dynamicAssembly.DefineDynamicModule("Main"); var dynamicType = dynamicModule.DefineType(newTypeName, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, typeof(T)); // This is the type of class to derive from. Use null if there isn't one dynamicType.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); foreach (var property in Properties) AddProperty(dynamicType, property.Key, property.Value); GeneratedType = dynamicType.CreateType(); }
在定义类型时,你能够提供一种类型,从中派生新的类型。若是你的基类具备要包含在新类型中的某些功能或属性,这将很是有用。以前,我曾使用它在运行时扩展ViewModel
和Serializable
类型。code
在你建立了TypeBuilder
后,你可使用下面提供的代码开始添加属性。它建立了支持字段和所需的中间语言,以便经过Getter
和Setter
访问它们。为每一个属性完成此操做后,可使用CreateType()
建立类型的实例。对象
private static void AddProperty(TypeBuilder typeBuilder, string propertyName, Type propertyType) { var fieldBuilder = typeBuilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private); var propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null); var getMethod = typeBuilder.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes); var getMethodIL = getMethod.GetILGenerator(); getMethodIL.Emit(OpCodes.Ldarg_0); getMethodIL.Emit(OpCodes.Ldfld, fieldBuilder); getMethodIL.Emit(OpCodes.Ret); var setMethod = typeBuilder.DefineMethod("set_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new[] { propertyType }); var setMethodIL = setMethod.GetILGenerator(); Label modifyProperty = setMethodIL.DefineLabel(); Label exitSet = setMethodIL.DefineLabel(); setMethodIL.MarkLabel(modifyProperty); setMethodIL.Emit(OpCodes.Ldarg_0); setMethodIL.Emit(OpCodes.Ldarg_1); setMethodIL.Emit(OpCodes.Stfld, fieldBuilder); setMethodIL.Emit(OpCodes.Nop); setMethodIL.MarkLabel(exitSet); setMethodIL.Emit(OpCodes.Ret); propertyBuilder.SetGetMethod(getMethod); propertyBuilder.SetSetMethod(setMethod); }
有了类型后,就很容易经过使用Activator.CreateInstance()
来建立它的实例。可是,你但愿可以更改已建立的属性的值,为了作到这一点,你能够再次使用反射来获取propertyInfos
并提取Set方法。一旦有了这些属性,电影它们类设置属性值就相对简单了。
foreach (var property in Properties) { var propertyInfo = GeneratedType.GetProperty(property.Key); var setMethod = propertyInfo.GetSetMethod(); setMethod.Invoke(objectInstance, new[] { propertyValue }); }
如今,您能够在运行时使用自定义属性来建立本身的类型,并具备更新其值的功能,一切就绪。 我发现的惟一障碍是建立一个能够存储新类型实例的列表。 WPF中的DataGrid倾向于只读取List的常规参数类型的属性。 这意味着即便您使用新属性扩展了基类,使用AutoGenerateProperties也只能看到基类中的属性。 解决方案是使用生成的类型显式建立一个新的List。 我在下面提供了如何执行此操做的示例:
var listGenericType = typeof(List<>); var list = listGenericType.MakeGenericType(GeneratedType); var constructor = list.GetConstructor(new Type[] { }); var newList = (IList)constructor.Invoke(new object[] { }); foreach (var value in values) newList.Add(value);
我已经在GitHub中建立了一个示例应用程序。它包含一个UI来帮助您调试和理解运行时新类型的建立,以及如何更新值。若是您有任何问题或意见,请随时与咱们联系。