【问题标题】:How do I do different things depending on the type of an argument (without using reflection)?如何根据参数的类型(不使用反射)做不同的事情?
【发布时间】:2018-04-06 01:42:40
【问题描述】:

我有一个接受泛型类型的函数,我希望能够根据该类型将某些计算的结果分配给不同的列表。我宁愿不使用反射,因为我知道这并不是最佳实践。

这是我目前所掌握的要点:

private List<int> List1 = new List<int>();
private List<int> List2 = new List<int>();
private List<int> List3 = new List<int>();

public int SomeFunction<TModel, TEntity>(DbSet<TEntity> context) where TEntity : class where TModel : SuperModel
{
    // TEntity could be one of three types: Type1, Type2, or Type3
    // If TEntity is of Type1, I want to be able to add something to List1.
    // If TEntity is of Type2, I want to be able to add something to List2.  And so on.

    /* One way to do it */

    // ... do some function stuff calculation here...
    var result = ...

    Type entity_type = typeof(TEntity)
    if (entity_type == typeof(Type1)) 
        List1.Add(result);
    else if (entity_type == typeof(Type2))
        List2.Add(result);
    else if (entity_type == typeof(Type3))
        List3.Add(result);
}

但是,我认为这不是最好的方法,因为它依赖于反射进行运行时计算。有没有办法使用接口或多态来做到这一点?

另一种方法是将其拆分为三个函数,让Type1Type2Type3 实现三个不同的接口,然后在每个接口后面添加where TEntity : IType1where TEntity: IType2where TEntity: IType3三个功能标题。

这似乎也不对。任何帮助将不胜感激。

【问题讨论】:

  • 有点违背了 generic 这样做的目的。泛型应该是不可知的,并且不知道具体类型,因为它限制了它的有用性
  • 您的示例代码虽然不是很优雅,但根本不依赖反射。
  • @MickyD 那么将其作为接口中的虚函数并让我的类型实现该接口并为他们自己的该函数版本提供代码会更好吗?
  • @noblerare 如果你正在做的事情可以做到,那将是一个更好的选择。
  • 看起来你最好不要使用泛型,只需使用 3 种不同的方法,一种用于 Type1Type2Type3。也会更快

标签: c#


【解决方案1】:

你描述的选项真的不多

  • 制作3个方法
  • 使用 IF
  • 使用模式匹配
  • 使用反射,虽然我不太清楚为什么
  • 你也可以使用开关

示例

switch typeof(e) { 
        case int:    ... break; 
        case string: ... break; 
        case double: ... break; 
        default:     ... break; 
}

或者你可以使类通用

public class SomeClass<T> where T : something
{

    private List<T> List3 = new List<T>();

    public int SomeFunction<TModel, T>(DbSet<T> context)
    {
        // do stuff
    }
}

【讨论】:

    【解决方案2】:

    您可以将pattern matchingis 关键字一起使用:

    if (context is DbSet<Type1>) 
    

    【讨论】:

      【解决方案3】:

      你可以用字典

      字典 d(custom_equality_comp)

      D.[entity_type].Add(result)

      有一段时间没有使用 c# 了,但这值得一试。 您在构造函数中初始化字典,然后从那里开始。 参考文献。

      Efficiency of using IEqualityComparer in Dictionary vs HashCode and Equals()

      Dictionary of generic lists or varying types

      List<Object> vs List<dynamic>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-07
        • 2022-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多