自动运行方法的 C# 属性

Jon*_*ear 2 custom-attributes c#-4.0

我不确定这是否完全可能。但我想做的是创建一个属性,当我调用 run 方法时,然后运行具有特定 run 属性的所有方法。我意识到这可以通过委托来完成,但我觉得如果可以通过属性来实现,看起来可能会更干净一些。我应该指出,运行顺序并不重要。

基本设计:

//This is the method called that should start off the attribute chain
public void Run(){
  //calling logic in here
}

[AutomatedRun]
private void Method1(){

}

[AutomatedRun]
private void Method2(){

}
Run Code Online (Sandbox Code Playgroud)

Ram*_*yev 6

在 C# 9.0 中引入了名为ModuleInitializer的新属性。如果您的 C# 版本大于或等于 9.0,则可以使用它。

我分享以下代码例如:

[System.Runtime.CompilerServices.ModuleInitializer]
internal static void SomeMethod()
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

欲了解更多详情,您可以访问这些链接:

模块初始值设定项 C# 9.0 草案规范,

如何在具体的实际用例中使用 .NET 模块初始值设定项

C# 9.0 中的模块初始值设定项