Skip to main content
 首页 » 编程设计

c#之找不到来自 mscorlib 的类型

2024年02月24日18EasonJim

有些事情我无法理解。我无法阅读类型引用:

Assembly mscorlib = Assembly.Load("mscorlib"); 
 
// it DOES exist, returns type reference: 
mscorlib.GetType("System.Deployment.Internal.Isolation.IDefinitionAppId"); 
 
// but its parent scope doesn't exist.. returns null: 
mscorlib.GetType("System.Deployment.Internal.Isolation");  
 
// even though it exists, it doesn't compile 
// System.Deployment.Internal.Isolation.IDefinitionAppId x; 

这怎么可能?

请您参考如下方法:

最后一行无法编译的原因是 IDefinitionAppId 是 internal - 而不是因为 System.Deployment.Internal.Isolation 是类型。

请注意,如果 Isolation 是类型的名称,则您必须使用 GetType("System.Deployment.Internal.Isolation+IDefinitionAppId")(注意+) 因为这是嵌套类型在 CLR 名称中的表示方式。

证明这一点非常简单:

using System; 
using System.Reflection; 
 
public class Test 
{ 
    static void Main() 
    { 
        Assembly mscorlib = typeof(string).Assembly; 
        string name = "System.Deployment.Internal.Isolation.IDefinitionAppId"; 
        Type type = mscorlib.GetType(name); 
 
        // Prints System.Deployment.Internal.Isolation 
        Console.WriteLine(type.Namespace); 
    } 
} 

所以 System.Deployment.Internal.Isolation 是命名空间,而不是类型,因此 Assembly.GetType(...) 找不到它作为类型。