指定子类(或任何类)作为返回类型时应该如何设置Apply
方法,以便当我调用它时,可以指定我想要的返回类型BaseResult
?当调用方法
目的是让调用代码知道是什么子类(实施BaseResult
),该应用将返回(再次,考虑到从IRequest
调用应用,而不是在它的实现)
的条件:
- 可能有许多实现
IRequest
- 可能有很多实现的
BaseResult
代码:
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
{
}
可以约束类型应用''需要一个'新的()'? –
AGB
您的代码不是通用的。如果你叫'Apply',怎么办?你会将一个'Result'投射到'AnotherResult',这在运行时会失败, –
@Dananley,这就是为什么我在这里,寻求其他人的想法和解决我的问题.. :) – stack247