c# - 如何在此示例方法中使用 (Switch) 而不是 (IF & Else)

标签 c# types if-statement switch-statement

我有一个由许多if 和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);
}

最佳答案

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

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

关于c# - 如何在此示例方法中使用 (Switch) 而不是 (IF & Else),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8373303/

相关文章:

c# - 如何在 C# 中反序列化 JSON(多级)

scala - 如何使用抽象类型的类型约束

python - 根据现有列中的某些规则在新数据框列中设置值

if-statement - 判断(if)中的nil值的更简单方法?

c# - 具有未绑定(bind)功能的 Odata : The related entity set or singleton cannot be found from the OData path

c# - Spy++ 无法到达 Qt 应用程序中的按钮

PostgreSql 将值存储为整数与 varchar

types - 类型 'float -> float' 与类型 'float' 不匹配

excel - 将 IF else 与 LEFT 组合以隐藏列

c# - 处理 for-each 循环中项目的异常