为什么`Assembly`和`Module`没有公开定义构造函数?函数、定义、Assembly、Module

2023-09-03 23:28:49 作者:回眸一笑凌乱了年华

我建立在C#.NET程序集加载器的一个实验/学习更多有关.NET的内部操作。我已经通过派生类型等实现的反射API:

I'm building a .NET assembly loader in C# for an "experiment"/learning more about .NET internal operations. I've implemented the reflection API by deriving types like:

RuntimeType:类型 RuntimeFieldInfo:字段信息 RuntimeMethodInfo:MethodInfo的 RuntimeParameterInfo:信息参数 RuntimeConstructorInfo:ConstructorInfo RuntimePropertyInfo:的PropertyInfo

不幸的是,我遇到了麻烦,因为下面有没有可公开访问的构造函数,所以我不能从他们那里获得:

Unfortunately I'm having trouble because the following have no publicly accessible constructors, so I can't derive from them:

在大会(不密封 - AssemblyBuilder内部来源于它) 在模块(不密封 - ModuleBuilder内部来源于它)

我需要的东西从 RuntimeType.get_Assembly 返回和 RuntimeType.get_Module 。建议?只要是有创意 - 我不得不。 ;),用于创建的RuntimeTypeHandle 情况下,指针的一些不安全的铸造能够完成任务,但它不是那么容易了这里。

I need something to return from RuntimeType.get_Assembly and RuntimeType.get_Module. Suggestions? Get creative - I've had to. ;) For creating RuntimeTypeHandle instances, some unsafe casting of pointers gets the job done, but it's not so easy here.

顺便说一句:在特定的麻烦,现在是我试图pretty的打印的IL为负载类型。对于构建仿制药,在 Type.FullName 财产包括通过 AssemblyQualifiedName 属性,而这又依赖于通用参数组装属性。

As an aside: The particular trouble now is I'm trying to pretty-print the IL for the loaded types. For constructed generics, the Type.FullName property includes the generic parameters via the AssemblyQualifiedName property, which in turn relies on the Assembly property.

推荐答案

为什么你不能从他们那里获得?这两种类型(大会和模块)中有一个受保护的构造,将提供给您的派生型。该类型本身是公共所以它比实际的说明不太明显的没有问题。

Why can't you derive from them? Both of the types (Assembly and Module) have a protected constructor that will be available to your derived type. The types themselves are public so there is no issue with it being less visible than the actual specifier.

下面code编译就好了

The following code compiles just fine

public class MyAssembly : System.Reflection.Assembly {
    public MyAssembly() : base() {}
}

至于为什么他们没有任何公开的构造函数。我没有这个任何直接的知识,但它似乎很清楚他们想迫使人们从这些类派生。它似乎奇怪考虑到他们没有抽象成员。我唯一​​能想到的是一个版本的问题,但背后没有任何逻辑是跳跃在我的脑海现在。

As to why they don't have any public constructors. I don't have any direct knowledge of this but it seems clear they wanted to force people to derive from these classes. It does seem odd considering they have no abstract members. The only thing I can think of is a versioning issue but no logic behind that is jumping to my mind right now.

修改

在我读280Z28的评论我检查,是的,这是新的.NET 4.0。在此之前4.0构造为大会和模块是内部和这两种类型是具体,但不密封。因此,推导之前的4.0也不是没有可能这样做有充分信任的code有些邪恶。

After I read 280Z28's comment I checked and yes this is new to .Net 4.0. Prior to 4.0 the constructor for both Assembly and Module was internal and both types were concrete but not sealed. So derivation prior to 4.0 is not possible without doing some evilness with fully trusted code.