如何使用(开关)代替(IF &Else)在这个示例方法中

本文关键字:方法 开关 何使用 代替 IF Else | 更新日期: 2023-09-27 18:16:40

我有一个方法由许多if and else。我如何通过Switch转换它?

protected override IRepository<T> CreateRepository<T>()
{
   if (typeof(T).Equals(typeof(Person)))
      return new PersonRepositoryNh(this, SessionInstance) as IRepository<T>;
   else if (typeof(T).Equals(typeof(Organization)))
      return new OrganizationRepositoryNh(this, SessionInstance) as IRepository<T>;
   else
      return new RepositoryNh<T>(SessionInstance);
}

如何使用(开关)代替(IF &Else)在这个示例方法中

根据规范,switch语句中只能使用sbyte、byte、short、ushort、int、uint、long、ulong、char、string或enum类型,因此基本上不能打开type对象。

现在,你要做的是打开Name的类型,这只是一个string,可以打开它

不能对类型Type使用switch语句。只能使用bool、char、string、integer和enum类型的开关,或者它们的可空版本。

根据编译器:

switch表达式或case标号必须是bool、char、string、整型、枚举或相应的可空类型

你不能。switchcase语句必须是编译时常量,类型为sbyte、byte、short、ushort、int、uint、long、ulong、char、string或enum类型(包括隐式转换),而Type对象不是这样的。

什么是合法的:

switch (foo)
{
    case 42:
       // code
       break;
}

什么是不合法的:

int value = GetValue(); // not a verifiable compile-time constant
switch (foo)
{
     case value: 
         // code
         break;
}
  1. 你确定要这样做吗?为什么不使用对象层次结构和虚函数?

public static void CreateTest<T>()
{
    switch (typeof(T).Name)
    {
        case "Int32": System.Console.WriteLine("int");
            break;
        case "String": System.Console.WriteLine("string");
            break;
    }
}
static void Main(string[] args)
{
    CreateTest<int>();
    CreateTest<string>();
    CreateTest<double>();
}