Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何遍历C#中的内置类型?_C# - Fatal编程技术网

如何遍历C#中的内置类型?

如何遍历C#中的内置类型?,c#,C#,我想遍历c#中的内置类型(bool、char、sbyte、byte、short、ushort等) 怎么做 foreach(var x in GetBuiltInTypes()) { //do something on x } 没有内置的方法可以做到这一点;您可以尝试: foreach (var type in new Type[] { typeof(byte), typeof(sbyte), ... }) { //... } 当然,如果要经常这样做,请将数组分解出来,并将其放入一个静

我想遍历c#中的内置类型(bool、char、sbyte、byte、short、ushort等)

怎么做

foreach(var x in GetBuiltInTypes())
{
//do something on x
}

没有内置的方法可以做到这一点;您可以尝试:

foreach (var type in new Type[] { typeof(byte), typeof(sbyte), ... })
{
    //...
}

当然,如果要经常这样做,请将数组分解出来,并将其放入一个
静态只读变量中。

这取决于如何定义课程的“内置”类型

您可能需要以下内容:

public static IEnumerable<Type> GetBuiltInTypes()
{
   return typeof(int).Assembly
                     .GetTypes()
                     .Where(t => t.IsPrimitive);
}
公共静态IEnumerable GetBuiltInTypes()
{
返回类型(int).Assembly
.GetTypes()
其中(t=>t.IsPrimitive);
}
这应该给你(从):

布尔型、字节型、SByte型、Int16型、UInt16型、Int32型、UInt32型、Int64型、UInt64型、IntPtr型、UIntPtr型、字符型、双精度和单精度

如果您有不同的定义,您可能希望枚举常见BCL程序集中的所有类型(如mscorlib、System.dll、System.Core.dll等),并在执行过程中应用过滤器。

是我能想到的最接近的方法

foreach(TypeCode t in Enum.GetValues(typeof(TypeCode)))
{ 
    // do something interesting with the value...
}

只有基元值类型?@Bolt:是的,只有基元值类型。因为它们是内置的(而且不可能很快改变,可能只是用所有类型创建一个枚举,然后用
foreach(MyEnumTypes中的类型builtInType)
…?这是无效的语法。你可能是指foreach(var Type in…)?@Cameron:oops,是的……我在想一半是D,一半是C。谢谢!:)我刚改了,是的,这是一个打字错误。啊,林克的美丽(和缓慢!)!这些解决方案总是富有创造性的。:)我们可以为所有内置基元类型(包括string、char、integer变量)创建一个函数
GetBuiltInTypes
?System.TypeCode将在一个位置提供string、char和integer变量。如果使用LINQ,我想最好使用
从typeof(int.Assembly.GetTypes()中的类型返回其中type.IsPrimitive选择类型取而代之;你觉得怎么样?:)@Mehrdad:在这种情况下,我对这两种语法没有强烈的偏好。依我看,两者都同样可读。我喜欢这个解决方案。非常感谢。对于其他解决方案,也感谢您。这里有一个“好答案”徽章:)