考虑这个通用类:
public class Request<TOperation>
where TOperation : IOperation
{
private TOperation _operation { get; set; }
public string Method { get { return _operation.Method; } }
public Request(TOperation operation)
{
_operation = operation;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的通用版本在下面的非通用版本中提供了哪些真正的好处?
public class Request
{
private IOperation _operation { get; set; }
public string Method { get { return _operation.Method; } }
public Request(IOperation operation)
{
_operation = operation;
}
}
Run Code Online (Sandbox Code Playgroud)
该IOperation接口是:
public interface IOperation
{
string Method { get; }
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*rth 14
使用通用版本,方法可以采用类型的参数Request<FooOperation>.传入一个实例Request<BarOperation>将无效.
因此,通用版本允许方法确保它们获得正确操作的请求.