温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么实现在运行时生成C#的.NET类

发布时间:2021-11-24 13:41:34 来源:亿速云 阅读:126 作者:iii 栏目:开发技术

这篇文章主要介绍“怎么实现在运行时生成C#的.NET类”,在日常操作中,相信很多人在怎么实现在运行时生成C#的.NET类问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么实现在运行时生成C#的.NET类”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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

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

  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 propertiesvar _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类型。

在你创建了 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);

到此,关于“怎么实现在运行时生成C#的.NET类”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI