泛型类中方法的不同返回类型

3 .net c# generics

以下代码刚刚组成,这可能与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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Amy*_*y B 6

你的愿望就是我的命令.

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

如果你想减少耦合,你可以选择:

public class MyMagicContainer<U>
{
  U GetStuff(Func<U> theFunc)
  {
    return theFunc()
  }
}
Run Code Online (Sandbox Code Playgroud)