c# - 与泛型类中的方法不同的返回类型

标签 c# .net 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();
    }
}

最佳答案

你的愿望就是我的命令。

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/

相关文章:

c# - 为什么 CLR 允许改变装箱的不可变值类型?

asp.net-mvc-3 - 在 Razor View 中与通用方法一起使用

c# - Json.Net 属性忽略所有属性

c# - FluentribbonTabItem 在设计器中不可见?

c# - 从插入中获取 session - C# 和 MySQL

c# - 串行端口通信丢失一个字节

c# - using 命名空间指令只能应用于命名空间

.net - 如何确定导致.NET线程停止的原因?

c - C 中的通用列表操作函数?

ios - Swift:通用类型符合协议(protocol)