C#类类型 - 如何确定它是否是标准的.net框架类

Hor*_*ter 5 c# reflection gettype

C#/ .net框架

确定类(类型)是否是.net框架提供的类而不是我的任何类或第三方库类的最可靠方法是什么.

我测试了一些方法

  • 命名空间,例如以"System"开头.
  • 程序集的代码库,dll所在的位置

所有这些"感觉"虽然有效,但有点笨拙.

问题:确定此问题的最简单,最可靠的方法是什么?

Chr*_*ich 6

您可以检查程序集的公钥令牌.Microsoft(BCL)程序集将具有公钥令牌b77a5c561934e089b03f5f7f11d50a3a.WPF程序集将具有公钥标记31bf3856ad364e35.

通常,要获取程序集的公钥标记,您可以使用. 是Windows SDK的一部分,您应该已经拥有它.sn.exe-Tp foo.dllsn.exe

您可以从程序集的全名(例如typeof(string).Assembly.FullName)获取公钥标记,这只是一个字符串,或者您可以通过对StrongNameTokenFromAssembly执行P/Invoke从程序集中获取原始公钥标记字节.


Raj*_*mal 2

从程序集读取程序集公司属性 [程序集:AssemblyCompany("Microsoft Corporation")]

http://msdn.microsoft.com/en-us/library/y1375e30.aspx

using System;
using System.Reflection;

[assembly: AssemblyTitle("CustAttrs1CS")]
[assembly: AssemblyDescription("GetCustomAttributes() Demo")]
[assembly: AssemblyCompany("Microsoft")]

namespace CustAttrs1CS {
    class DemoClass {
        static void Main(string[] args) {
            Type clsType = typeof(DemoClass);
            // Get the Assembly type to access its metadata.
            Assembly assy = clsType.Assembly;

            // Iterate through the attributes for the assembly.
            foreach(Attribute attr in Attribute.GetCustomAttributes(assy)) {
                // Check for the AssemblyTitle attribute.
                if (attr.GetType() == typeof(AssemblyTitleAttribute))
                    Console.WriteLine("Assembly title is \"{0}\".",
                        ((AssemblyTitleAttribute)attr).Title);

                // Check for the AssemblyDescription attribute.
                else if (attr.GetType() == 
                    typeof(AssemblyDescriptionAttribute))
                    Console.WriteLine("Assembly description is \"{0}\".",
                        ((AssemblyDescriptionAttribute)attr).Description);

                // Check for the AssemblyCompany attribute.
                else if (attr.GetType() == typeof(AssemblyCompanyAttribute))
                    Console.WriteLine("Assembly company is {0}.",
                        ((AssemblyCompanyAttribute)attr).Company);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)