检测是否一个​​对象的类型是由.NET框架中定义的类型 [英] Detect if the type of an object is a type defined by .NET Framework

查看:66
本文介绍了检测是否一个​​对象的类型是由.NET框架中定义的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何能够通过反射确定一个对象的类型是一类在自己的装配或由.NET Framework定义?

How can I determine by reflection if the type of an object is defined by a class in my own assembly or by the .NET Framework?

我不想提供自己的汇编代码的名字,因为它应该与任何组装和命名工作。

I dont want to supply the name of my own assembly in code, because it should work with any assembly and namespace.

推荐答案

哪来第三方类型进来吗?你可能希望它声称微软,哪些不需要类型提供类型之间的区别

Where would third-party types come in? You might want to differentiate between types which claim to be provided by Microsoft and types which don't.

using System;
using System.Linq;
using System.Reflection;

class Test
{
    static void Main()
    {
        Console.WriteLine(IsMicrosoftType(typeof(string)));
        Console.WriteLine(IsMicrosoftType(typeof(Test)));
    }

    static bool IsMicrosoftType(Type type)
    {
        object[] attrs = type.Assembly.GetCustomAttributes
            (typeof(AssemblyCompanyAttribute), false);

        return attrs.OfType<AssemblyCompanyAttribute>()
                    .Any(attr => attr.Company == "Microsoft Corporation");
    }
}



当然,任何类型的可能的要求的是微软1给出这个方案,但如果你实际上只是要调用它自己的类型和框架的人,我怀疑这应该可以正常工作。

Of course, any type could claim to be a Microsoft one given this scheme, but if you're actually only going to call it on your own types and framework ones, I suspect this should work fine.

另外,你可以使用该程序集的公钥标记。这很可能是更难伪造。它使用他们所有的组件一个共同的公共密钥,他们不依赖于微软(根据以下迈赫达德的评论)。但是,你可以很容易适应这种解决方案的的设置接受的,这是来自微软的公共密钥的。也许在某种程度上将二者结合起来的方法和报告进行进一步的检查...

Alternatively, you could use the assembly's public key token. This is likely to be harder to fake. It relies on Microsoft using a common public key for all their assemblies, which they don't (according to Mehrdad's comment below). However, you could easily adapt this solution for a set of accepted "this is from Microsoft" public keys. Perhaps combine the two approaches somehow and report any differences for further inspection...

static bool IsMicrosoftType(Type type)
{
    AssemblyName name = type.Assembly.GetName();
    byte[] publicKeyToken = name.GetPublicKeyToken();

    return publicKeyToken != null
        && publicKeyToken.Length == 8
        && publicKeyToken[0] == 0xb7
        && publicKeyToken[1] == 0x7a
        && publicKeyToken[2] == 0x5c
        && publicKeyToken[3] == 0x56
        && publicKeyToken[4] == 0x19
        && publicKeyToken[5] == 0x34
        && publicKeyToken[6] == 0xe0
        && publicKeyToken[7] == 0x89;
}

这篇关于检测是否一个​​对象的类型是由.NET框架中定义的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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