【发布时间】: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);
}
但是,我认为这不是最好的方法,因为它依赖于反射进行运行时计算。有没有办法使用接口或多态来做到这一点?
另一种方法是将其拆分为三个函数,让Type1、Type2、Type3 实现三个不同的接口,然后在每个接口后面添加where TEntity : IType1、where TEntity: IType2 和where TEntity: IType3三个功能标题。
这似乎也不对。任何帮助将不胜感激。
【问题讨论】:
-
有点违背了 generic 这样做的目的。泛型应该是不可知的,并且不知道具体类型,因为它限制了它的有用性
-
您的示例代码虽然不是很优雅,但根本不依赖反射。
-
@MickyD 那么将其作为接口中的虚函数并让我的类型实现该接口并为他们自己的该函数版本提供代码会更好吗?
-
@noblerare 如果你正在做的事情可以做到,那将是一个更好的选择。
-
看起来你最好不要使用泛型,只需使用 3 种不同的方法,一种用于
Type1、Type2和Type3。也会更快
标签: c#