如何确定System.Type是自定义类型还是框架类型? [英] How do I determine if System.Type is a custom type or a Framework type?

查看:30
本文介绍了如何确定System.Type是自定义类型还是框架类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想明确地确定我拥有的类型是自定义类类型(MyClass)还是框架提供的类型(System.String).

I want to distinctly determine if the type that I have is of custom class type (MyClass) or one provided by the Framework (System.String).

有什么反映可以区分我的类类型与system.string或其他Framework提供的类型吗?

Is there any way in reflection that I can distinguish my class type from system.string or other Framework provided types?

推荐答案

安全检查类型是否为程序集的一部分的唯一方法是检查程序集的全限定名称,该名称包含其名称,版本,区域性和公共密钥(如果已签名).Microsoft使用其私钥对所有.Net基类库(BCL)进行签名.这使得其他任何人几乎都不可能创建一个与基类库具有完全相同名称的程序集.

The only way to safely check if a type is part of an assembly is to check the assembly's fully qualified name which contains its name, version, culture and public key (if signed). All .Net base class libraries (BCL) are signed by microsoft using their private keys. This makes it almost impossible for anyone else to create an assembly with same fully qualified name as a base class library.

//add more .Net BCL names as necessary
var systemNames = new HashSet<string>
{
"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
};

var isSystemType = systemNames.Contains(objToTest.GetType().Assembly.FullName); 

较不那么脆弱的解决方案是使用 AssemblyName 类并跳过版本号/区域性检查.当然,这假定公钥在版本之间不变.

A slightly less brittle solution is to use the AssemblyName class and skip the version number/culture check. This of course assumes the public key doesn't change between versions.

//add more .Net BCL names as necessary
var systemNames = new List<AssemblyName>
{
new AssemblyName ("mscorlib, Version=4.0.0.0, Culture=neutral, " +
                  "PublicKeyToken=b77a5c561934e089"),
new AssemblyName ("System.Core, Version=4.0.0.0, Culture=neutral, "+
                  "PublicKeyToken=b77a5c561934e089")
};

var obj = GetObjectToTest();

var objAN = new AssemblyName(obj.GetType().Assembly.FullName);

bool isSystemType = systemNames.Any(
        n =>  n.Name == objAN.Name 
           && n.GetPublicKeyToken().SequenceEqual(objAN.GetPublicKeyToken()));

大多数BCL已使用相同的密钥签名,但不是全部.您可以使用AssemblyName类仅检查公共密钥令牌.这取决于您的需求.

Most of the BCL have been signed with the same key but not all. You could use the AssemblyName class to just check the public key token. It depends on your needs.

这篇关于如何确定System.Type是自定义类型还是框架类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆