我有这样的事情:
public [What Here?] GetAnything()
{
Hello hello = new Hello();
Computer computer = new Computer();
Radio radio = new Radio();
return radio; or return computer; or return hello //should be possible?!
}
Run Code Online (Sandbox Code Playgroud)
我有一个方法,这个方法有时会返回不同类型的值(类).
我怎么能这样做,以后再使用变量,是radio.Play(); 到目前为止?
我需要使用泛型吗?怎么样?
Mar*_*ell 42
如果没有共同的基类型或接口,那么public object GetAnything() {...}- 但通常最好采用某种抽象,例如通用接口.例如,如果Hello,Computer并Radio全部实行IFoo,那么它可能返回IFoo.
RQD*_*QDQ 38
以下是使用泛型的方法:
public T GetAnything<T>()
{
T t = //Code to create instance
return t;
}
Run Code Online (Sandbox Code Playgroud)
但是您必须知道在设计时返回的类型.这意味着你可以为每个创作调用一个不同的方法......
Ric*_*ers 14
如果您可以为所有可能性创建一个抽象类,那么强烈建议:
public Hardware GetAnything()
{
Computer computer = new Computer();
return computer;
}
abstract Hardware {
}
class Computer : Hardware {
}
Run Code Online (Sandbox Code Playgroud)
或者一个界面:
interface IHardware {
}
class Computer : IHardware {
}
Run Code Online (Sandbox Code Playgroud)
如果它可以是任何东西,那么你可以考虑使用"object"作为返回类型,因为每个类都派生自object.
public object GetAnything()
{
Hello hello = new Hello();
return hello;
}
Run Code Online (Sandbox Code Playgroud)
tbt*_*tbt 14
Marc的答案应该是正确的答案,但在.NET 4中你不能使用动态类型.
只有当你无法控制你返回的类并且没有共同的祖先(通常使用interop)时才应该使用它,并且只有在不使用dynamic时才会使用(在每个步骤中转换每个对象:).
很少有博客文章试图解释何时使用动态:http://blogs.msdn.com/b/csharpfaq/archive/tags/dynamic/
public dynamic GetSomething()
{
Hello hello = new Hello();
Computer computer = new Computer();
Radio radio = new Radio();
return // anyobject
}
Run Code Online (Sandbox Code Playgroud)
Abh*_*jha 13
使用dynamic关键字作为返回类型.
private dynamic getValuesD<T>()
{
if (typeof(T) == typeof(int))
{
return 0;
}
else if (typeof(T) == typeof(string))
{
return "";
}
else if (typeof(T) == typeof(double))
{
return 0;
}
else
{
return false;
}
}
int res = getValuesD<int>();
string res1 = getValuesD<string>();
double res2 = getValuesD<double>();
bool res3 = getValuesD<bool>();
Run Code Online (Sandbox Code Playgroud)
问候,
作者Abhijit
aw0*_*w04 10
要使用泛型来建立@RQDQ的答案,您可以将其与Func<TResult>(或某些变体)结合并将责任委托给调用者:
public T GetAnything<T>(Func<T> createInstanceOfT)
{
//do whatever
return createInstanceOfT();
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
Computer comp = GetAnything(() => new Computer());
Radio rad = GetAnything(() => new Radio());
Run Code Online (Sandbox Code Playgroud)