mub*_*her 3 .net c# asp.net generics asp.net-mvc
我想调用一个方法接受T type对象。在我的自定义方法中,我收到了T type。如何将我传递T type给已经接收到的方法T type?可以通过反射来调用吗?
下面是我的方法:
public IEnumerable<T> Method2<T>(string fileSrc, char sep)
{
// Using LinqToCsv lib
IEnumerable<T> list;
CsvFileDescription inputFileDescription = new CsvFileDescription
{
SeparatorChar = sep,//specify the separator line
FirstLineHasColumnNames = true //Header is in the first line
};
CsvContext csvContext = new CsvContext();
list = csvContext.Read<T>(fileSrc, inputFileDescription);
// Data is now available via variable list.
return list;
}
Run Code Online (Sandbox Code Playgroud)
在上面的方法 csvContext.Read<T>(fileSrc, inputFileDescription);中声明为
public IEnumerable<T> Read<T>(string fileName, CsvFileDescription fileDescription)
where T : class, new();
Run Code Online (Sandbox Code Playgroud)
我将感谢您的帮助。
调用泛型方法时,需要确保type参数匹配相同的泛型约束。
因此,您需要将方法声明更改为
public IEnumerable<T> Method2<T>(string fileSrc, char sep) where T : class, new()
Run Code Online (Sandbox Code Playgroud)
为了调用Read<T>()需要其Ttype参数匹配这些约束的方法。