加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

是否有一种优雅的方法可以让类中的每个方法都以C#中的某个代码块

发布时间:2020-12-15 18:13:39 所属栏目:百科 来源:网络整理
导读:我有一个类,每个方法都以相同的方式启动: internal class Foo { public void Bar() { if (!FooIsEnabled) return; //... } public void Baz() { if (!FooIsEnabled) return; //... } public void Bat() { if (!FooIsEnabled) return; //... }} 对于类中的每
我有一个类,每个方法都以相同的方式启动:
internal class Foo {
  public void Bar() {
    if (!FooIsEnabled) return;
    //...
  }
  public void Baz() {
    if (!FooIsEnabled) return;
    //...
  }
  public void Bat() {
    if (!FooIsEnabled) return;
    //...
  }
}

对于类中的每个公共方法,是否有一种很好的方法来要求(并且希望不是每次都写入)FooIsEnabled部分?

我检查Is there an elegant way to make every method in a class start with a certain block of code?,但这个问题是针对Java的,其答案是使用Java Library.

解决方法

您正在寻找的主要是来自 Aspect Oriented Programming或AOP域的拦截.

虽然C#不直接支持它,但有坚实的选择:

> Postsharp
> Unity Interception
> Spring.NET
> Castle Interceptors

如果我明天有空,我会为你做一个例子……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读