dynamic return type of a function

后端 未结 5 1033
春和景丽
春和景丽 2021-02-07 04:46

How can I create a function that will have a dynamic return type based on the parameter type?

Like

protected DynamicType Test(DynamicType type)
{

retur         


        
相关标签:
5条回答
  • 2021-02-07 05:09

    Whilst the accepted answer is good, it has been over two years since it was written, so, I should add that you can use:

    protected dynamic methodname(dynamic input)
    {
        return input;
    }
    

    Input will be returned as the same type, and you do not need to call the method as a generic.

    Reference:
    https://msdn.microsoft.com/en-us/library/dd264736.aspx

    0 讨论(0)
  • 2021-02-07 05:11

    C# is not a dynamic language. To tackle this problem in C# you can return a generic object and typecast later to whatever you think the value should be -- not recommended. You can also return an interface, this way you don't really care about a specific class instance. As others have pointed out you can also use generics. It really depends on what you need / want to do inside the body of the function since all the methods above have their own limitations.

    0 讨论(0)
  • 2021-02-07 05:14

    You'd have to use generics for this. For example,

    protected T Test<T>(T parameter)
    {
    
    }
    

    In this example, the '<T>' tells the compiler that it represents the name of a type, but you don't know what that is in the context of creating this function. So you'd end up calling it like...

    int foo;
    
    int bar = Test<int>(foo);
    
    0 讨论(0)
  • 2021-02-07 05:14

    Actually, assuming that you have a known set of parameters and return types, it could be handled with simple overloading:

    protected int Test(string p) {   ...  }
    protected string Test(DateTime p ) { .... }
    
    0 讨论(0)
  • 2021-02-07 05:20

    Then you need use generics.

    protected T Test(T type) {
    
    return type;
    
    }
    
    0 讨论(0)
提交回复
热议问题