我有一个传递IEnumerable<TModel>
的方法。然后,根据TModel
的类型,该方法执行以下指令集:
public void MyMethod<TModel>(IEnumerable<TModel> items) where TModel : class
{
int operationType;
switch (typeof(TModel))
{
case typeof(MyModelOne):
operationType = 1;
break;
case typeof(MyModelTwo):
operationType = 2;
break;
case typeof(MyModelThree):
operationType = 3;
break;
default:
throw new Exception("The collection model passed to MyMethod is not recognized");
}
...
}
这不起作用,我得到了错误:
没有应用程序变量或成员“ TModel”
最佳答案
您无法打开Type
变量。用级联if
语句替换它。
if (typeof(TModel) == typeof(MyModelOne)) {
operationType = 1;
} else if (typeof(TModel) == typeof(MyModelTwo)) {
operationType = 2;
} // ...
关于c# - C#获取IEnumerable <TModel>的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2882556/