下面的代码是自己编的,用C#可以吗?
class A
{
public int DoStuff()
{
return 0;
}
}
class B
{
public string DoStuff()
{
return "";
}
}
class MyMagicGenericContainer<T> where T : A, B
{
//Below is the magic <------------------------------------------------
automaticlyDetectedReturnTypeOfEitherAOrB GetStuff(T theObject)
{
return theObject.DoStuff();
}
}
最佳答案
你的愿望就是我的命令。
public interface IDoesStuff<T>
{
T DoStuff();
}
public class A : IDoesStuff<int>
{
public int DoStuff()
{ return 0; }
}
public class B : IDoesStuff<string>
{
public string DoStuff()
{ return ""; }
}
public class MyMagicContainer<T, U> where T : IDoesStuff<U>
{
U GetStuff(T theObject)
{
return theObject.DoStuff();
}
}
如果你想要更少的耦合,你可以选择:
public class MyMagicContainer<U>
{
U GetStuff(Func<U> theFunc)
{
return theFunc()
}
}
关于c# - 与泛型类中的方法不同的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/982949/