切换PropertyType

Bor*_*ens 28 c# switch-statement

我怎样才能做到这一点?

switch(property.PropertyType){
    case typeof(Boolean): 
        //doStuff
        break;
    case typeof(String): 
        //doOtherStuff
        break;
    default: break;
}
Run Code Online (Sandbox Code Playgroud)

我不想使用这个名字,因为字符串比较类型很糟糕,可能会有所变化.

Jor*_*ira 46

        System.Type propertyType = typeof(Boolean);
        System.TypeCode typeCode = Type.GetTypeCode(propertyType);
        switch (typeCode)
        {
            case TypeCode.Boolean:
                //doStuff
                break;
            case TypeCode.String:
                //doOtherStuff
                break;
            default: break;
        }
Run Code Online (Sandbox Code Playgroud)

您可以对TypeCode.Object使用混合方法,使用typeof进行动态处理.这非常快,因为对于第一部分 - 交换机 - 编译器可以基于查找表来决定.

  • 只需注意一下,如果你想让它适用于Nullable类型,你必须检查propertyType.IsGenericType && propertyType.GetGenericTypeDefinition()== typeof(System.Nullable <>),然后获取基础类型......这里是一个例子:http://www.yakkowarner.com/2008/12/propertyinfopropertytype-is-it-nullable.html (6认同)
  • 如果你想比较简单的内置类型以外的任何东西将无法工作,因为TypeCode是一个枚举,不容纳任何东西,但像bool,int32等简单类型... (3认同)