gpt4 book ai didi

c# - Nsubstitute:如何在泛型类中创建一个假的

转载 作者:太空宇宙 更新时间:2023-11-03 12:25:37 28 4
gpt4 key购买 nike

我正在使用 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
}
}

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

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[])'

这似乎很明显,因为 Substitute 的实现类看起来像这样:

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

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

最佳答案

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

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 约束。

关于c# - Nsubstitute:如何在泛型类中创建一个假的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45192167/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com