C# 函数的动态返回类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/744401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:29:22  来源:igfitidea点击:

dynamic return type of a function

c#

提问by DevMania

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

如何创建一个基于参数类型具有动态返回类型的函数?

Like

喜欢

protected DynamicType Test(DynamicType type)
{

return ; 

}

采纳答案by Adam Robinson

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...

在这个例子中,' <T>' 告诉编译器它代表一个类型的名称,但是你不知道在创建这个函数的上下文中它是什么。所以你最终会这样称呼它......

int foo;

int bar = Test<int>(foo);

回答by J.W.

Then you need use generics.

然后你需要使用泛型。

protected T Test(T type) {

return type;

}

回答by James Curran

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 ) { .... }

回答by pbz

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.

C# 不是动态语言。要在 C# 中解决这个问题,您可以返回一个泛型对象,然后将其类型转换为您认为该值应该是什么——不推荐。您还可以返回一个接口,这样您就不必真正关心特定的类实例。正如其他人指出的那样,您也可以使用泛型。这实际上取决于您在函数体内需要/想要做什么,因为上述所有方法都有其自身的局限性。

回答by Wil

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

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