2017-07-19 83 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