2013-02-12 20 views
10

考慮這個泛型類:C#泛型 - 通過使包裝類具有通用性而獲得了什麼?

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; 
    } 
} 

哪些實實在在的好處呢通用版本以上報價在低於此非通用版本?

public class Request 
{ 
    private IOperation _operation { get; set; } 

    public string Method { get { return _operation.Method; } } 

    public Request(IOperation operation) 
    { 
     _operation = operation; 
    } 
} 

IOperation接口是:

public interface IOperation 
{ 
    string Method { get; } 
} 

回答

13

隨着通用版本的方法可以採取Request<FooOperation>類型的參數。傳入Request<BarOperation>的實例將無效。
因此,通用版本使方法能夠確保他們獲得正確操作的請求。

+0

Gotcha - 所以換句話說,它允許您在需要消費的位置更加嚴格地「關閉」或指定「請求」類型,但無需爲不同的操作類型創建自定義的「請求」對象。 – MalcomTucker 2013-02-12 15:08:05

+0

@ MalcomTucker:正確。 – 2013-02-12 15:10:39

3

例如,如果你有

public class SubOperation : IOperation 
{ 
    // implementation ... 
} 

public class OtherSubOperation : IOperation 
{ 
    // implementation ... 
} 

你可以確保請求不可能舉行OtherSubOperation項目,但他們都將是有效的IOperations。

4

在你上面給出的情況下,很難說什麼好處你得到,這將取決於如何,這是在你的代碼庫中使用,但考慮到以下幾點:

public class Foo<T> 
    where T : IComparable 
{ 
    private T _inner { get; set; } 

    public Foo(T original) 
    { 
     _inner = original; 
    } 

    public bool IsGreaterThan<T>(T comp) 
    { 
     return _inner.CompareTo(comp) > 0; 
    } 
} 

反對

public class Foo    
    { 
     private IComparable _inner { get; set; } 

     public Foo(IComparable original) 
     { 
      _inner = original; 
     } 

     public bool IsGreaterThan(IComparable comp) 
     { 
      return _inner.CompareTo(comp) > 0; 
     } 
} 

如果再有一個Foo<int>,你可能不希望把它比作Foo<string>,但將沒有鎖定下來使用非通用版本的方式。

11

除了所有其他很好的答案,我會補充說如果你碰巧構建Request<T>T這是實現IOperation值類型的通用版本不走裝箱損失。每次都有非通用版本框。