Jim*_*mbo 1 c# generics collections types
我有一个方法,我通过了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");
}
...
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,我收到错误:
没有应用程序变量或memeber'TModel'
您无法打开Type变量.用级联if语句替换它.
if (typeof(TModel) == typeof(MyModelOne)) {
operationType = 1;
} else if (typeof(TModel) == typeof(MyModelTwo)) {
operationType = 2;
} // ...
Run Code Online (Sandbox Code Playgroud)