如何在使用类型的switch-case? [英] How to use switch-case on a Type?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/298976/c-sharp-is-there-a-better-alternative-than-this-to-switch-on-type\">C# - 是否有比这更好的替代品上式开关'
我需要通过我的课的所有属性进行迭代,并检查其类型的int我需要做的事情,如果它的字符串..然后做一些事情。我需要使用它的switch-case。在这里,我使用了以下方式切换,但它要求一些常量。看到下面的code:
I need to iterate through all properties of my class and to check if its type of int the i need to do something, if its string .. then do something. I need it using switch-case. Here i am using switch in the following manner, but it asks for some constant. see the code below:
public static bool ValidateProperties(object o)
{
if(o !=null)
{
var sourceType = o.GetType();
var properties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (var property in properties)
{
var type = property.GetType();
switch (type)
{
*case typeof(int):* getting error here
// d
}
}
}
}
此外,我想知道,我应该用什么检查的typeof(INT)或typeof运算(Int32)已?
Also i want to know , what check should I use, typeof(int) or typeof(Int32)?
推荐答案
您不能使用交换机组测试类型的值键入
。编译code应该给你一个错误,说是这样的:
You cannot use a switch block to test values of type Type
. Compiling your code should give you an error saying something like:
一个开关前pression或case标签必须为BOOL,CHAR,字符串,
积分,枚举,或相应的可空类型
A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type
您需要使用如果
- 其他
语句来代替
You'll need to use if
-else
statements instead.
另外: typeof运算(INT)
和 typeof运算(Int32)已
是等价的。 INT
是一个关键字和的Int32
是类型名称。
Also: typeof(int)
and typeof(Int32)
are equivalent. int
is a keyword and Int32
is the type name.
更新
如果您预计大多数类型将是内在则可以通过使用一个开关块与 Type.GetType code(...)
提高性能。
If you expect that most types will be intrinsic you may improve performance by using a switch block with Type.GetTypeCode(...)
.
例如:
switch (Type.GetTypeCode(type))
{
case TypeCode.Int32:
// It's an int
break;
case TypeCode.String:
// It's a string
break;
// Other type code cases here...
default:
// Fallback to using if-else statements...
if (type == typeof(MyCoolType))
{
// ...
}
else if (type == typeof(MyOtherType))
{
// ...
} // etc...
}
这篇关于如何在使用类型的switch-case?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!