How do I determine if System.Type is a custom type or a Framework type?

前端 未结 5 898
情书的邮戳
情书的邮戳 2020-12-17 17:45

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).

Is there any way in refle

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 18:29

    If you simply want to distinguish between MyClass and string then you can check for those types directly:

    Type typeToTest = GetTypeFromSomewhere();
    
    if (typeToTest == typeof(MyClass))
        MyClassAction();
    else if (typeToTest == typeof(string))
        StringAction();
    else
        NotMyClassOrString();
    

    If you need a more general check for whether or not a given type is a framework type then you could check whether it belongs to the System namespace:

    // create an array of the various public key tokens used by system assemblies
    byte[][] systemTokens =
        {
            typeof(System.Object)
                .Assembly.GetName().GetPublicKeyToken(),  // B7 7A 5C 56 19 34 E0 89
            typeof(System.Web.HttpRequest)
                .Assembly.GetName().GetPublicKeyToken(),  // B0 3F 5F 7F 11 D5 0A 3A 
            typeof(System.Workflow.Runtime.WorkflowStatus)
                .Assembly.GetName().GetPublicKeyToken()   // 31 BF 38 56 AD 36 4E 35 
        };
    
    Type typeToTest = GetTypeFromSomewhere();
    
    string ns = typeToTest.Namespace;
    byte[] token = typeToTest.Assembly.GetName().GetPublicKeyToken();
    
    bool isSystemType = ((ns == "System") || ns.StartsWith("System."))
                        && systemTokens.Any(t => t.SequenceEqual(token));
    

提交回复
热议问题