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

前端 未结 5 889
情书的邮戳
情书的邮戳 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条回答
  •  Happy的楠姐
    2020-12-17 18:40

    Not all framework classes start in the System namespace (they can also be Microsoft etc).

    As such, you could probably compare the location of a known framework class with that of the type that you are testing such as:

      if (String.CompareOrdinal(
            Path.GetDirectoryName(typeof(String).Assembly.Location), 
            Path.GetDirectoryName(typeof(MyType).Assembly.Location)
          ) == 0)
      {
        //Framework Type
      }
      else
      {
        //3rd Party DLL
      }
    

    Not the greatest solution; but safer than just testing if the namespace starts with System (I could create a namespace that starts with System that isn't a framework class).

    Edit

    Also, in addition to the above test, it wouldn't hurt to verify that the type is loaded from the Global Assembly Cache:

    typeof(MyType).Assembly.GlobalAssemblyCache
    

提交回复
热议问题