在类的所有方法之前运行一个方法 [英] Run a method before all methods of a class

查看:29
本文介绍了在类的所有方法之前运行一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 C# 3 或 4 中做到这一点?也许有一些反思?

Is it possible to do that in C# 3 or 4? Maybe with some reflection?

class Magic
{

    [RunBeforeAll]
    public void BaseMethod()
    {
    }

    //runs BaseMethod before being executed
    public void Method1()
    {
    }

    //runs BaseMethod before being executed
    public void Method2()
    {
    }
}

编辑

对此有一个替代解决方案,使 Magic 成为单例,并将您的代码放在静态实例的 getter 上.这就是我所做的:

There is an alternate solution for this, make Magic a singleton and put your code on the getter of the static instance. That's what I did:

public class Magic
{

    private static Magic magic = new Magic();
    public static Magic Instance
    {
        get
        {
            magic.BaseMethod();
            return magic;
        }
    }

    public void BaseMethod()
    {
    }

    //runs BaseMethod before being executed
    public void Method1()
    {
    }

    //runs BaseMethod before being executed
    public void Method2()
    {
    }
}

推荐答案

您不能在 C# 中自动执行此操作 - 您可能应该查看 AOP,例如使用 PostSharp.

You can't do this automatically in C# - you should probably be looking at AOP, e.g. with PostSharp.

这篇关于在类的所有方法之前运行一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆