简体   繁体   中英

different return type from method in generic class

The following code is just made up, is this possible to do with 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();
    }
}

Your wish is my command.

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();
  }
}

If you want less coupling, you could go with:

public class MyMagicContainer<U>
{
  U GetStuff(Func<U> theFunc)
  {
    return theFunc()
  }
}

The method that ends up calling automaticlyDetectedReturnTypeOfEitherAOrB() would have to know the return type though. Unless you make the method return object. Then the calling method can get back whatever (int or string) and figure out what to do with it.

Another option is to do something like this: (sorry, I don't have VisStudio open to validate syntax or that it works right)

R GetStuff<R>(T theObject)
{
    return (R)theObject.DoStuff();
}

void Method1()
{
    int i = GetStuff<int>(new A());
    string s = GetStuff<string>(new B());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM