C#泛型 - 通过使包装类通用获得什么?

Mal*_*ker 11 .net c# generics

考虑这个通用类:

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>将无效.
因此,通用版本允许方法确保它们获得正确操作的请求.


Eri*_*ert 12

除了所有其他好的答案之外,我还要补充一点,如果您碰巧Request<T>使用T实现的值类型构造,则通用版本不会受到限制IOperation.每次都是非通用版本框.