gpt4 book ai didi

c# - 如何检查一个类的所有公共(public)方法都是虚拟的

转载 作者:行者123 更新时间:2023-12-02 05:17:50 25 4
gpt4 key购买 nike

在 .net 项目中,有很多实体是用 C# 实现的。使用的库(传奇实体的 nservicebus)的要求是所有访问方法都声明为公共(public)和虚拟的,否则在部署过程中会失败。

在单元测试阶段检查实体的访问方法是否为虚拟是合理的,s.a.部署可能需要很长时间(在它被发现之前)

有谁知道在 nunit 测试中检查一个类中的所有公共(public)方法是否都声明为虚拟方法的好方法?

最佳答案

我使用某种相同的测试来验证,游戏引擎包装器将所有公共(public)方法都作为虚拟方法。它使测试更容易,并且可以显着减少反馈时间。我将这些方法放在特殊类 DesignTests 下,我在其中测试,例如,我的项目中没有违反约定。有一些复杂的事情,FxCop 无法检测到。你可以看到下面的代码:

[Test]
public void AllPublicMethodsInUnityFacade_ShouldBeVirtual()
{
var allPublicMethods =
typeof(UnityFacade).GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);

Assert.IsTrue(allPublicMethods.All(method => method.IsVirtual),
string.Join(", ", allPublicMethods
.Where(method => !method.IsVirtual)
.Select(method => method.Name))
+ " is not virtual");

}

关于c# - 如何检查一个类的所有公共(public)方法都是虚拟的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14358652/

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