简体   繁体   中英

Method return type like Generic Class Type

Is possible set method return type, like type to generic class ?

I have Generic Class:

    class Generic<T>
    {
        public static DataSet test(T input)
        {
         //Some logic...
        }
    }

Another Class, where i call my generic class.

It works for this examples:

Generic<int>.test(10);

But if i want to call different methods, with complex unknown date types, i don't know how i put their date type like Generic Type.

For Example

var data = Data.GetData(); // return List<string,int>
var data2 = Data.GetData2() // return Tuple<List<string>, List<int>>

I try use method GetType, for get returns method type, something like this, but it doesn't work.

Generic<data.GetType()>.test(data);

Is it possible, something like this ?

No, you can't specify the generic type at runtime without reflection, but there may be other ways to solve your problem. You could put the generic constraint on the method instead of the class:

class Generic
{
    public static dynamic Test<T>(T input)
    {
     //Some logic...
    }
}

which then can be inferred from the input type:

Generic.Test(data);

Return Type of a function is known in compile time. Therefore if I understood your question correctly what you're asking for isn't possible. TL;DR You can't set return type in runtime.

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