[英]How to pass Type as a Parameter to Method
我是 C# 的新手,但是在尝试将TableOne
类型 class 传递给方法并在方法本身中使用时遇到了问题。
Class:
public class TableOne
{
public List<string> CaseID { get; set; }
public List<string> Owner { get; set; }
public List<string> Assignee { get; set; }
public List<string> Comments { get; set; }
}
方法:
public static string ComposeHtmlTable<T>(Type classType, IList<T> table)
{
List<classType> test = table.Cast<classType>().ToList();
Console.WriteLine(test[0].CaseID[0]); // trying to access data
return "test";
}
如何调用该方法:
ComposeHtmlTable<TableOne>(typeof(TableOne), data.TableOne);
我收到错误:
'classType' is a variable but is used like a type.
该方法必须使用参数类型的原因是因为可能有多种类型,即我可能传递给该方法的TableTwo
或TableThree
。
关于如何解决这个问题的任何想法?
TIA
问题出在这行代码List<classType> test = table.Cast<classType>().ToList();
List<classType>
和Cast<classType>
是无效的语法。 List<T>
是可以接受的。
c# 中的 arguments 类型分别发送到变量。 您已经将类型参数 T 提供给泛型方法。 所以请改用List<T>
和Cast<T>
。
因此,将 classType 作为变量传入是多余的。
即使您需要对提供的元素类型进行 switch 表达式,您也可以打开typeof(T)
正如@Dai 建议的那样,您可以用泛型类型参数替换classType
参数:
static List<T1> ComposeHtmlTable<T1,T2>(IList<T2> table)
{
List<T1> test = table.Cast<T1>().ToList();
return test;
}
PS:我更改了您的方法以返回新列表,因为我认为这就是您想要实现的目标...
并称它为:
ComposeHtmlTable<TableOne,TableOne>(data.TableOne);
如果这两种泛型类型总是相同的,您可以将该方法简化为:
static List<T> ComposeHtmlTable<T>(IList<T> table)
{
return (List<T>) table.Cast<T>().ToList();
}
并称之为:
ComposeHtmlTable<TableOne>(data.TableOne);
让我们看一下classType
和T
:
public static string ComposeHtmlTable<T>(Type classType, IList<T> table)
{
List<classType> test = table.Cast<classType>().ToList();
Console.WriteLine(test[0].CaseID[0]); // trying to access data
return "test";
}
它们可以是一些任意类型,比如T == int
和classType == StringBuider
吗? 当然不。 如我所见, classType
和T
都应该从TableOne
继承。 让我们 .net 知道吧:
public static string ComposeHtmlTable<C, T>(IList<T> table)
where C : TableOne
where T : TableOne
{...}
是时候添加一些细节了:
IList<T> table
作为参数, IEnumerable<T> table
就足够了(我们不仅可以通过数组传递列表)public
,任何输入都是可能的; 所以我们必须验证输入 argumentstest
是空的(即它没有任何项目?)。 在这种情况下,我们无法获取test[0].CaseID[0]
。public static string ComposeHtmlTable<C, T>(IEnumerable<T> table)
where C : TableOne
where T : TableOne
{
if (table is null)
throw new ArgumentNullException(nameof(table));
List<C> test = table.Cast<C>().ToList();
if (test.Count > 0 && test[0] != null && test[0].CaseID.Count > 0)
Console.WriteLine(test[0].CaseID[0]); // trying to access data
else
Console.WriteLine("test is empty");
return "test";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.