【问题标题】:How use of (Switch) instead of (IF & Else) in this sample method在此示例方法中如何使用 (Switch) 而不是 (IF & Else)
【发布时间】:2011-12-04 04:41:05
【问题描述】:

我有很多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);
}

【问题讨论】:

    标签: c# types if-statement switch-statement


    【解决方案1】:

    根据specificationswitch 语句中只能使用 sbyte、byte、short、ushort、int、uint、long、ulong、char、string 或 enum-types,所以基本上你不能打开type 对象。

    现在,你可以做的就是打开类型的Name,那只是一个string,打开就可以了。

    【讨论】:

    • 谢谢。但是使用Name是硬编码,不适合。
    【解决方案2】:

    您不能对类型 Type 使用 switch 语句。您只能使用带有 bool、char、string、integral 和 enum 或它们的可为空版本的开关。

    根据编译器:

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

    【讨论】:

      【解决方案3】:

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

      什么是合法的:

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

      什么是不合法的:

      int value = GetValue(); // not a verifiable compile-time constant
      
      switch (foo)
      {
           case value: 
               // code
               break;
      }
      

      【讨论】:

      • typeof(something) 是编译时间
      • typeof(something) 也不是受支持的类型之一,也不能隐式转换为受支持的类型之一。
      【解决方案4】:
      1. 您确定要这样做吗?为什么不使用对象层次结构和虚函数?

      2. 此代码有效

      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>();
      
      }
      

      【讨论】:

        猜你喜欢
        • 2020-10-14
        • 2023-02-20
        • 1970-01-01
        • 2010-10-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 2021-01-09
        • 1970-01-01
        相关资源
        最近更新 更多