我有一个接受泛型类型的函数,我希望能够根据该类型将某些计算的结果分配给不同的列表。我宁愿不使用反射,因为我了解到这并不是最佳实践。
这是我到目前为止的要点:
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
下面这三个功能标题。
这似乎也不对。任何帮助将不胜感激。
你所描述的真的没有很多选择
例子
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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句