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