2017-07-19 74 views
2

我正在使用Nsubstitute進行嘲諷。爲了減少代碼我想寫的是假貨的一般屬性的通用類:Nsubstitute:如何在通用類中創建一個虛假內容

public class Tester<TValue> 
    where TValue: IValue 
{ 
    // this is used inside the class in other methods 
    private TValue CreateValue() 
    { 
     return Substitute.For<TValue>(); // here the compiler has an error 
    } 
} 

該代碼給出了在標記的地方編譯錯誤:

類型「TValue」必須是引用類型爲了 在通用類型或方法使用它作爲參數「T」 「Substitute.For(params對象[])」

這似乎明顯,因爲Substitute類的實現看起來是這樣的:

public static class Substitute 
{ 
    public static T For<T>(params object[] constructorArguments) where T : class; 
} 

我想知道的是,爲什麼那麼這樣的代碼是可能的:Substitute.For<IValue>(),並不會引發錯誤。任何人都可以解釋如何通過僞造權來完成泛型類嗎?

回答

1

下面的代碼應該工作:

public class Tester<TValue> 
    where TValue : class, IValue 
{ 
    // this is used inside the class in other methods 
    private TValue CreateValue() 
    { 
     return Substitute.For<TValue>(); // here the compiler has an error 
    } 
} 

The type must be a reference type in order to use it as parameter 'T' in the generic type or method可能是值得一讀。

有必要的原因是Substitute.For指定了一個參考類型(class)。因此,任何通用呼叫者(如你自己)都需要指定相同的約束條件。

+0

感謝您的回覆。我看到了這個約束,NSubstitute需要一個類作爲通用參數。我想知道,可以使用'Substitute.For ()'的接口。對我來說,不可能將'TValue'泛型參數約束爲一個類,因爲我需要它用於接口。 – scher

+0

您是否可以使用IValue的接口定義(即文件)更新您的文章,以及實現IValue的每個類/結構的文件? – mjwills

+0

請注意,在我的代碼示例中,「class」並不意味着「類而不是接口」,這意味着「類而不是結構」。你有沒有嘗試我的上述代碼用於你的目的?它有用嗎? – mjwills