mardi 12 avril 2016

Specifying child class as return type when Invoke method

Based on my classes below, how should I setup Apply method so that when I call it, I can specify what BaseResult return type that I want?

The conditions are:

  • There could be many implementations of IRequest
  • There could be many implementations of BaseResult

Code:

void Main()
{
    // For example purpose, let's pretend 'myreq' is retrieved from reflection. So, there's no way I would know it's type of MyRequest. And there will be many other implementations of IRequest.
    var req = new MyRequest();

    var request = (IRequest)req;

    // How should I setup Apply method so that when I call the method, I can specify what BaseResult return type that I want?
    // In this example, I would like Apply method to return Result type, which inherits from BaseResult.
    var res = req.Apply<Result>();
}

// Define other methods and classes here
public interface IRequest
{
    string GetValue();
    T Apply<T>() where T : BaseResult;
}

public class MyRequest : IRequest
{
    // How should I setup Apply method to allow returning any BaseResult I want? Each IRequest implementation of Apply method may return different BaseResult type.
    public T Apply<T>() where T : BaseResult
    {
        // Doesn't work here
        // Can't implicitly convert type BaseResult to T
        return (BaseResult) new Result();
    }

    public string GetValue() { return string.Empty; }
}

public class Result : BaseResult
{
    public string Message { get; set;}
}

public class AnotherResult : BaseResult
{
    public string Message { get; set; }
}

public class BaseResult
{
}

Aucun commentaire:

Enregistrer un commentaire