指定子類(或任何類)作爲返回類型時應該如何設置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