简体   繁体   中英

How to pass generic type to generic method?

I want to invoke a method accepting T type object. In my custom method I'm receiving T type . How can I pass my T type to the method which is already receiving a T type ? Can it be invoked via reflection?

Below is my method:

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;
}

In the above method csvContext.Read<T>(fileSrc, inputFileDescription); is declared as

public IEnumerable<T> Read<T>(string fileName, CsvFileDescription fileDescription) 
    where T : class, new();

I will be grateful for the help.

When you call a generic method you need to make sure that the type parameter matches the same generic constraints.

So you need to change your method declaration to

public IEnumerable<T> Method2<T>(string fileSrc, char sep) where T : class, new()

in order to invoke the the Read<T>() method which requires its T type argument to match these constraints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM