在运行时生成C# .NET类

​本文译自​:​Generating C# .NET Classes at Runtime
作者:WedPort

在我的C#职业生涯中,有几次我不得不在运行时生成新的类型。希望把它写下来能帮助有相同应用需求的人。这也意味着我以后不必在查找相同问题的StackOverflow文章了。我最初是在.NET 4.6.2中这样做的,但我已经更新到为.NET Core 3.0提供了示例。所有代码都可以在我的GitHub上面找到。
GitHub:https://github.com/cheungt6/public/tree/master/ReflectionEmitClassGeneration

为什么我需要在运行时生成类?

在运行时生产新类型的需求通常是由于运行时才知道类属性,满足性能要求以及需要在新类型中添加功能。当你尝试这样做的时候,你应该考虑的第一件事是:这是否真的是一个明智的解决方案。在深入思考之前,还有很多其他事情可以尝试,问你自己这样的问题:

  1. 我可以使用普通的类吗
  2. 我可以使用Dictionary、Tuple或者对象数组(Array)?
  3. 我是否可以使用扩展对象
  4. 我确定我不能使用一个普通的类吗?

如果你认为这仍然是必要的,请继续阅读下面的内容。

示例用例

作为一名开发人员,我将大量数据绑定到各种WPF Grids中。大多数时候属性是固定的,我可以使用预定义的类。有时候,我不得不动态的构建网格,并且能够在应用程序运行时更改数据。采取以下显示ID和一些财务数据的类(FTSE和CAC是指数,其属性代表指数价格):

public class PriceHolderViewModel : ViewModelBase
{
    public long Id { get; set; }
    public decimal FTSE100 { get; set; }
    public decimal CAC40 { get; set; }
}

如果我们仅对其中的属性感兴趣,该类定义的非常棒。但是,如果要使用更多属性扩展此类,则需要在代码中添加它,重新编译并在新版本中进行部署。

相反的,我们可以做的是跟踪对象所需的属性,并在运行时构建类。这将允许我们在需要是不断的添加和删除属性,并使用反射来更新它们的值。

// 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();
}

在定义类型时,你可以提供一种类型,从中派生新的类型。如果你的基类具有要包含在新类型中的某些功能或属性,这将非常有用。之前,我曾使用它在运行时扩展ViewModelSerializable类型。

在你创建了TypeBuilder后,你可以使用下面提供的代码开始添加属性。它创建了支持字段和所需的中间语言,以便通过GetterSetter访问它们。为每个属性完成此操作后,可以使用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来帮助您调试和理解运行时新类型的创建,以及如何更新值。如果您有任何问题或意见,请随时与我们联系。
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值