【问题标题】:Is it possible to get some kind of base method thats always called?是否有可能获得某种总是被调用的基本方法?
【发布时间】:2012-07-29 02:16:43
【问题描述】:

我有一个抽象的数据提供者,有很多方法。

在实现中,每个方法都需要进行一些检查,然后才能继续执行其余的方法。这个检查总是一样的。

所以现在在每种方法中,我都会这样做:

public override string Method1 {
    if(myCheck()) throw new Exception(...);
    ...Rest of my method1...
}
public override string Method2 {
    if(myCheck()) throw new Exception(...);
    ...Rest of my method2...
}
public override string Method3 {
    if(myCheck()) throw new Exception(...);
    ...Rest of my method3...
}

你明白了..

有没有更简单/更好/更短的方法来做到这一点?

【问题讨论】:

  • 这里的内容被称为“面向方面的编程”。搜索该术语可能会产生一些有用的信息。
  • 谢谢,我去看看
  • 一个小的改进是包括在 myCheck 中抛出异常,因此每个方法只需要调用 myCheck() - 你可以摆脱 if 语句并抛出。
  • 出于兴趣什么叫你的方法?你的基类中有什么东西?
  • @ChrisMoutray,其代码来自业务层调用此数据层中的方法。 “基础类”是什么意思?

标签: c# aop implementation


【解决方案1】:

C# 中没有内置功能。不过,您可以在 PostSharp 中进行操作。

public sealed class RequiresCheckAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionEventArgs e)
    {
        // Do check here.
    }
}

如果您想在纯 C# 中执行此操作,可以让您的生活更轻松的小改进是将代码重构为单独的方法:

public void throwIfCheckFails() {
    if(myCheck()) throw new Exception(...);
}

public override string Method1 {
    throwIfCheckFails();
    // ...Rest of my method1...
}

这不会强制每个方法都执行检查 - 它只是让它更容易。

【讨论】:

    【解决方案2】:

    您可以通过以下方式实现基类:

    public virtual string MethodCalledByMethod1 {
    }
    
    public virtual string MethodCalledByMethod2 {
    }
    
    public virtual string MethodCalledByMethod3 {
    }
    
    public string Method1 {
        if(myCheck()) throw new Exception(...);
        return MethodCalledByMethod1();
    }
    public string Method2 {
        if(myCheck()) throw new Exception(...);
        return MethodCalledByMethod2();
    }
    public string Method3 {
        if(myCheck()) throw new Exception(...);
        return MethodCalledByMethod3();
    }
    

    然后在你的子类中

    public override string MethodCalledByMethod1 {
        ...Rest of my method1...
    }
    
    public override string MethodCalledByMethod2 {
        ...Rest of my method1...
    }
    
    public override string MethodCalledByMethod3 {
        ...Rest of my method1...
    }
    

    基本上,您会覆盖由基类实现调用的方法 1 到 3。基类实现包含 mycheck(),因此您只需担心编写一次(即在基类实现中)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多