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>()
,並不會引發錯誤。任何人都可以解釋如何通過僞造權來完成泛型類嗎?
感謝您的回覆。我看到了這個約束,NSubstitute需要一個類作爲通用參數。我想知道,可以使用'Substitute.For()'的接口。對我來說,不可能將'TValue'泛型參數約束爲一個類,因爲我需要它用於接口。 –
scher
您是否可以使用IValue的接口定義(即文件)更新您的文章,以及實現IValue的每個類/結構的文件? – mjwills
請注意,在我的代碼示例中,「class」並不意味着「類而不是接口」,這意味着「類而不是結構」。你有沒有嘗試我的上述代碼用於你的目的?它有用嗎? – mjwills