在运行时生成C# .NET类
<p>本文译自:Generating C# .NET Classes at Runtime<br>作者:WedPort</p>
<p>在我的C#职业生涯中,有几次我不得不在运行时生成新的类型。希望把它写下来能帮助有相同应用需求的人。这也意味着我以后不必在查找相同问题的StackOverflow文章了。我最初是在.NET 4.6.2中这样做的,但我已经更新到为.NET Core 3.0提供了示例。所有代码都可以在我的GitHub上面找到。<br>
GitHub:https://github.com/cheungt6/public/tree/master/ReflectionEmitClassGeneration</p>
<h2 id="为什么我需要在运行时生成类">为什么我需要在运行时生成类?</h2>
<p>在运行时生产新类型的需求通常是由于运行时才知道类属性,满足性能要求以及需要在新类型中添加功能。当你尝试这样做的时候,你应该考虑的第一件事是:这是否真的是一个明智的解决方案。在深入思考之前,还有很多其他事情可以尝试,问你自己这样的问题:</p>
<ol>
<li>我可以使用普通的类吗</li>
<li>我可以使用Dictionary、Tuple或者对象数组(Array)?</li>
<li>我是否可以使用扩展对象</li>
<li>我确定我不能使用一个普通的类吗?</li>
</ol>
<p>如果你认为这仍然是必要的,请继续阅读下面的内容。</p>
<h2 id="示例用例">示例用例</h2>
<p>作为一名开发人员,我将大量数据绑定到各种WPF Grids中。大多数时候属性是固定的,我可以使用预定义的类。有时候,我不得不动态的构建网格,并且能够在应用程序运行时更改数据。采取以下显示ID和一些财务数据的类(FTSE和CAC是指数,其属性代表指数价格):</p>
<pre><code>public class PriceHolderViewModel : ViewModelBase
{
public long Id { get; set; }
public decimal FTSE100 { get; set; }
public decimal CAC40 { get; set; }
}
</code></pre>
<p>如果我们仅对其中的属性感兴趣,该类定义的非常棒。但是,如果要使用更多属性扩展此类,则需要在代码中添加它,重新编译并在新版本中进行部署。</p>
<p>相反的,我们可以做的是跟踪对象所需的属性,并在运行时构建类。这将允许我们在需要是不断的添加和删除属性,并使用反射来更新它们的值。</p>
<pre><code>// 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) ) });
</code></pre>
<h2 id="创建你的类型">创建你的类型</h2>
<p>下面的示例向您展示了如何在运行时构建新类型。你需要使用<code>**System.Reflection.Emit**</code>库来构造一个新的动态程序集,您的类将在其中创建,然后是模块和类型。与旧的<code>** .NET Framework**</code>框架不同,在旧的版本中,你需要在当前程序的<code>AppDomain</code>中创建程序集 ,而在<code>** .NET Core** </code>中,<code>AppDomain</code>不再可用。你将看到我使用GUID创建了一个新类型名称,以便于跟踪类型的版本。在以前,你不能创建具有相同名称的两个类型,但是现在似乎不是这样了。</p>
<pre><code>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();
}
</code></pre>
<p>在定义类型时,你可以提供一种类型,从中派生新的类型。如果你的基类具有要包含在新类型中的某些功能或属性,这将非常有用。之前,我曾使用它在运行时扩展<code>ViewModel</code>和<code>Serializable</code>类型。</p>
<p>在你创建了<code>TypeBuilder</code>后,你可以使用下面提供的代码开始添加属性。它创建了支持字段和所需的中间语言,以便通过<code>Getter</code>和<code>Setter</code>访问它们。为每个属性完成此操作后,可以使用<code>CreateType()</code>创建类型的实例。</p>
<pre><code>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);
}
</code></pre>
<p>有了类型后,就很容易通过使用<code>Activator.CreateInstance()</code>来创建它的实例。但是,你希望能够更改已创建的属性的值,为了做到这一点,你可以再次使用反射来获取<code>propertyInfos</code>并提取Set方法。一旦有了这些属性,电影它们类设置属性值就相对简单了。</p>
<pre><code>foreach (var property in Properties)
{
var propertyInfo = GeneratedType.GetProperty(property.Key);
var setMethod = propertyInfo.GetSetMethod();
setMethod.Invoke(objectInstance, new[] { propertyValue });
}
</code></pre>
<p>现在,您可以在运行时使用自定义属性来创建自己的类型,并具有更新其值的功能,一切就绪。 我发现的唯一障碍是创建一个可以存储新类型实例的列表。 WPF中的DataGrid倾向于只读取List的常规参数类型的属性。 这意味着即使您使用新属性扩展了基类,使用AutoGenerateProperties也只能看到基类中的属性。 解决方案是使用生成的类型显式创建一个新的List。 我在下面提供了如何执行此操作的示例:</p>
<pre><code>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);
</code></pre>
<h2 id="结论">结论</h2>
<p>我已经在GitHub中创建了一个示例应用程序。它包含一个UI来帮助您调试和理解运行时新类型的创建,以及如何更新值。如果您有任何问题或意见,请随时与我们联系。<br>
<img src="https://img2020.cnblogs.com/blog/1746998/202006/1746998-20200622132327830-2129604186.gif"></p>
</div>
<div id="MySignature" role="contentinfo">
<div>作者:芝麻麻雀</div>
<div>出处:https://www.cnblogs.com/sesametech-netcore/</div>
<div>本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。 </div><br><br>
来源:https://www.cnblogs.com/sesametech-dotnet/p/13176329.html
頁:
[1]