How to determine if a object type is a built in system type

前端 未结 8 971
醉酒成梦
醉酒成梦 2020-12-14 00:20

I am writing a simple List to CSV converter. My converter checks the all the t\'s in List and grabs all public properties and places them

相关标签:
8条回答
  • 2020-12-14 00:47

    If you are unable to define precisely what a "built in system type" is then it seems likely that you won't know what types are in any answer given. More probably what you want to do is just have a list of the types that you don't want to do this with. Have a "IsSimpleType" method that just does a check against various types.

    The other thing that you may be looking for is Primitive Types. If so look at:

    Type.IsPrimitive (http://msdn.microsoft.com/en-us/library/system.type.isprimitive.aspx)

    The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.

    This doesn't include string but you could add that on manually...

    See also How To Test if Type is Primitive

    0 讨论(0)
  • 2020-12-14 00:51

    I think this is the best possibility:

    private static bool IsBulitinType(Type type)
    {
        return (type == typeof(object) || Type.GetTypeCode(type) != TypeCode.Object);
    }
    
    0 讨论(0)
  • 2020-12-14 00:53

    myName.GetType().Namespace
    This will return System if it is an in-built type.

    0 讨论(0)
  • 2020-12-14 00:53

    I was building something reflectively and found that the IsSecurityCritical property seemed to work for this purpose; however, this was only because the trust-level for my assembly wasn't high enough to flip that bit.

    A bit of a laugh; thankfully I found this question and will be adjusting accordingly.

    Note: The IsSecurityCritical property only exists if .NetFramework > 4

    I will likely go with; the following from a previous answer.

    myName.GetType().Module.ScopeName == "CommonLanguageRuntimeLibrary"

    But, with a couple tweaks; such as making it an extension method on Type and using a const for CommonLanguageRuntimeLibrary

    0 讨论(0)
  • 2020-12-14 00:57

    Here are a few of the several possibilities:

    • myName.GetType().Namespace == "System"
    • myName.GetType().Namespace.StartsWith("System")
    • myName.GetType().Module.ScopeName == "CommonLanguageRuntimeLibrary"
    0 讨论(0)
  • 2020-12-14 01:00

    Given the caveats surrounding the existing answers, I am going to suggest a Windows only solution:

    public static class TypeExt {
        public static bool IsBuiltin(this Type aType) => new[] { "/dotnet/shared/microsoft", "/windows/microsoft.net" }.Any(p => aType.Assembly.CodeBase.ToLowerInvariant().Contains(p));
    }
    

    Presumably there is a similar path on other supported operating systems.

    0 讨论(0)
提交回复
热议问题