gpt4 book ai didi

c# - C#获取IEnumerable 的类型

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:17 25 4
gpt4 key购买 nike

我有一个传递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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com