Bil*_*eal 155 c# reflection
可能重复:
如何找到调用当前方法的方法?
我想编写一个方法来获取调用方法的名称,以及包含调用方法的类的名称.
有可能用C#反射吗?
BFr*_*ree 415
public class SomeClass
{
public void SomeMethod()
{
StackFrame frame = new StackFrame(1);
var method = frame.GetMethod();
var type = method.DeclaringType;
var name = method.Name;
}
}
Run Code Online (Sandbox Code Playgroud)
现在让我们说你有另一个这样的类:
public class Caller
{
public void Call()
{
SomeClass s = new SomeClass();
s.SomeMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
名称将为"呼叫",类型将为"呼叫者"
更新两年后,我仍然对此有所了解
在.Net 4.5中,现在有一种更简单的方法可以做到这一点.你可以利用CallerMemberNameAttribute
继上一个例子:
public class SomeClass
{
public void SomeMethod([CallerMemberName]string memberName = "")
{
Console.WriteLine(memberName); //output will be name of calling method
}
}
Run Code Online (Sandbox Code Playgroud)
Are*_*ren 21
您可以使用它来使用它StackTrace,然后您可以从中获得反射类型.
StackTrace stackTrace = new StackTrace(); // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
Console.Write(method.Name);
Console.Write(method.DeclaringType.Name);
Run Code Online (Sandbox Code Playgroud)
ckr*_*mer 11
实际上,可以使用当前堆栈跟踪数据和反射的组合来完成.
public void MyMethod()
{
StackTrace stackTrace = new System.Diagnostics.StackTrace();
StackFrame frame = stackTrace.GetFrames()[1];
MethodInfo method = frame.GetMethod();
string methodName = method.Name;
Type methodsClass = method.DeclaringType;
}
Run Code Online (Sandbox Code Playgroud)
在1上索引StackFrame数组会给你这调用的方法MyMethod
从技术上讲,你可以使用StackTrace,但这很慢,并且不会给你很多时候所期望的答案.这是因为在发布版本中,可能会发生删除某些方法调用的优化.因此,您无法确定在发布时堆栈跟踪是否"正确".
真的,在C#中没有任何万无一失或快速的方法.您应该问自己为什么需要这个以及如何构建应用程序,这样您就可以在不知道调用它的方法的情况下做您想做的事情.
| 归档时间: |
|
| 查看次数: |
113592 次 |
| 最近记录: |