Nsubstitute:如何在泛型中创建伪造 class

Nsubstitute: How to create a fake inside a generic class

我正在使用 Nsubstitute 进行模拟。为了减少代码,我想编写一个伪造通用属性的通用 class:

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

这段代码在标记的地方给出了编译错误:

The type 'TValue' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Substitute.For(params object[])'

这似乎很明显,因为 Substituteclass 的实现如下所示:

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

我想知道的是,为什么这样的代码是可能的:Substitute.For<IValue>() 并且不会引发错误。任何人都可以解释如何使用伪造权进行通用 class 吗?

下面的代码应该可以工作:

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)。因此,它的任何通用调用者(比如你自己)都需要指定相同的 class 约束。