Mar*_*mić 6 .net c# reflection
我有一个基类,它有一个由派生类执行的方法.该方法由派生类的构造函数以及其中的某些方法或属性引发.我需要确定它是来自该派生类的实例构造函数内部还是之后(在运行时).
以下示例说明了我需要的内容:
public class Base
{
public Base()
{
}
protected void OnSomeAction(object sender)
{
// if from derived constructor EXIT, else CONTINUE
}
}
public class Derived : Base
{
public void Raise()
{
base.OnSomeAction(this); // YES if not called by constructor
}
public Derived()
{
base.OnSomeAction(this); // NO
Raise(); // NO
}
}
class Program
{
static void Main(string[] args)
{
var c = new Derived(); // NO (twice)
c.Raise(); // YES
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我无法更改签名或参数,因为我无法更改派生类.基本上我的想法是确定派生类(发送者)是否完全构造.
所以实现就是这样.我不能在打破派生类的基类中进行更改.我只能对基类进行更改:/
这有可能以某种方式,好还是不好?不幸的是,即使是一些反思魔法或类似的hacky方法也是受欢迎的,因为这是必须的:/.
谢谢!
这有可能以某种方式......
是
好还是不好?
不.但你已经知道了.
不过,这是一种方法.
protected void OnSomeEvent( object sender, EventArgs e )
{
var trace = new StackTrace();
var frames = trace.GetFrames();
for ( int idx = 0; idx < frames.Length; idx++ )
{
MethodBase method;
method = frames[idx].GetMethod();
if ( method.ReflectedType == typeof(Derived) && method.IsConstructor )
{
return;
}
}
/* Perform action */
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2233 次 |
| 最近记录: |