简体   繁体   English

方法返回类型,如通用类类型

[英]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. 我尝试使用方法GetType,用于获取返回方法类型,类似这样,但是它不起作用。

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. TL; DR您无法在运行时设置返回类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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