一个类的所有方法之前运行的方法 [英] Run a method before all methods of a class
本文介绍了一个类的所有方法之前运行的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能做到这一点在C#3或4?也许有一些反思?
类魔术{
[RunBeforeAll]
公共无效BaseMethod (){
}
//执行
之前运行BaseMethod公共无效方法1(){
}
//运行BaseMethod之前被执行
公共无效方法2(){
}
}
感谢
编辑--------------------------
有是这样的一个替代的解决方案,使魔独立的,并把你的代码的静态实例的getter。这就是我所做的。
公共类魔术{
私有静态魔幻=全新Magic() ;
公共静态魔术实例{
得到
{
magic.BaseMethod();
返回魔术;
}
}
公共无效BaseMethod(){
}
//执行之前运行BaseMethod
公共无效方法1(){
}
//执行之前运行BaseMethod
公共无效方法2(){
}
}
解决方案
有是这样的一个替代的解决方案,让魔术单并把你的代码静态实例的getter。 。这就是我所做的。
公共类魔术{
私有静态幻幻;
公共静态魔术实例{
得到
{
BaseMethod();
返回魔术;
}
}
公共无效BaseMethod(){
}
//执行之前运行BaseMethod
公共无效方法1(){
}
//执行之前运行BaseMethod
公共无效方法2(){
}
}
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(){
}
}
Thanks
EDIT--------------------------
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(){
}
}
解决方案
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;
public static Magic Instance{
get
{
BaseMethod();
return magic;
}
}
public void BaseMethod(){
}
//runs BaseMethod before being executed
public void Method1(){
}
//runs BaseMethod before being executed
public void Method2(){
}
}
这篇关于一个类的所有方法之前运行的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文