如何确定对象类型是否为内置系统类型

Jer*_*emy 39 .net c# reflection types

我正在编写一个简单List<t>的CSV转换器.我的转换器检查tList中的所有内容并获取所有公共属性并将它们放入CSV中.

当您使用具有一些属性的简单类时,我的代码很有效(按预期).

我想让List<t>CSV转换器也接受系统类型,如String和Integer.使用这些系统类型,我不想获得它们的公共属性(例如Length,Chars等).因此,我想检查对象是否是系统类型.按系统类型我的意思是内置的.Net类型之一,如string, int32, double等.

使用GetType()我可以找到以下内容:

string myName = "Joe Doe";

bool isPrimitive = myName.GetType().IsPrimitive; // False
bool isSealed = myName.GetType().IsSealed; // True 
// From memory all of the System types are sealed.
bool isValueType = myName.GetType().IsValueType; // False

// LinqPad users: isPrimitive.Dump();isSealed.Dump();isValueType.Dump();
Run Code Online (Sandbox Code Playgroud)

如何找到变量myName是否为内置系统类型?(假设我们不知道它的字符串)

Gab*_*abe 54

以下是几种可能性中的一些:

  • myName.GetType().Namespace == "System"
  • myName.GetType().Namespace.StartsWith("System")
  • myName.GetType().Module.ScopeName == "CommonLanguageRuntimeLibrary"

  • @JeremyChild`System.Security.Cryptography.Pkcs.SignedCms`类型具有`Module.ScopeName`等于`System.Security.dll`,因此不仅应该检查一个`"CommonLanguageRuntimeLibrary"`.我添加了像`moduleScope =="CommonLanguageRuntimeLibrary"||的检查 moduleScope.StartsWith("System")|| sourceType.Namespace.StartsWith("System")|| sourceType.Namespace.StartsWith( "微软")` (3认同)
  • 这些都很棒!Module ScopeName是一种可靠的方法.谢谢! (2认同)

Its*_*ete 39

myName.GetType().Namespace
如果它是内置类型,这将返回System.

  • 这回答了问题,但没有解决问题.你怎么知道`System`命名空间中的所有值类型都是你可以忽略属性的?你真的想对`System.ArgIterator`或`System.Nullable <Employee>`这样做吗? (11认同)
  • 您不需要在字符串上调用`ToString`. (6认同)
  • @NetMage,程序员可以使用不同程序集中的自定义类型来扩展系统名称空间。如果我们使用字符串命名空间,我们可能会得到不正确的结果,因为这种类型不是*语言内置* (new System.CustomType().GetType().Namespace) == "System" (2认同)

Chr*_*ris 10

如果您无法准确定义"内置系统类型"是什么,那么您似乎不会知道给出的任何答案中的类型.更可能你想要做的只是列出你不想做的类型.有一个"IsSimpleType"方法,只检查各种类型.

您可能正在寻找的另一件事是原始类型.如果是这样看:

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

基元类型是布尔,字节,SByte,Int16,UInt16,Int32,UInt32,Int64,UInt64,IntPtr,UIntPtr,Char,Double和Single.

这不包括字符串,但您可以手动添加...

另请参见如何测试类型是否为基元


Mak*_*man 7

基于命名空间的方法可能会导致冲突。

还有另一种可靠而简单的方法:

static bool IsSystemType(this Type type) => type.Assembly == typeof(object).Assembly;
Run Code Online (Sandbox Code Playgroud)

或更优一些,缓存系统程序集:

static readonly Assembly SystemAssembly = typeof(object).Assembly;

static bool IsSystemType(this Type type) => type.Assembly == SystemAssembly;
Run Code Online (Sandbox Code Playgroud)


k3f*_*flo 6

我认为这是最好的可能性:

private static bool IsBulitinType(Type type)
{
    return (type == typeof(object) || Type.GetTypeCode(type) != TypeCode.Object);
}
Run Code Online (Sandbox Code Playgroud)