Cam*_*ron 174
当前班级名称:
this.GetType().Name;
Run Code Online (Sandbox Code Playgroud)
当前方法名称:
using System.Reflection;
// ...
MethodBase.GetCurrentMethod().Name;
Run Code Online (Sandbox Code Playgroud)
由于您将此用于记录目的,您可能还有兴趣获取当前堆栈跟踪.
小智 9
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType
Run Code Online (Sandbox Code Playgroud)
我将上面的示例稍微更改为这段工作示例代码:
public class MethodLogger : IDisposable
{
public MethodLogger(MethodBase methodBase)
{
m_methodName = methodBase.DeclaringType.Name + "." + methodBase.Name;
Console.WriteLine("{0} enter", m_methodName);
}
public void Dispose()
{
Console.WriteLine("{0} leave", m_methodName);
}
private string m_methodName;
}
class Program
{
void FooBar()
{
using (new MethodLogger(MethodBase.GetCurrentMethod()))
{
// Write your stuff here
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Program.FooBar enter
Program.FooBar leave
Run Code Online (Sandbox Code Playgroud)
小智 5
是的!MethodBase 类的静态 GetCurrentMethod 将检查调用代码以查看它是构造函数还是普通方法,并返回 MethodInfo 或 ConstructorInfo。
此命名空间是反射 API 的一部分,因此您基本上可以通过使用它来发现运行时可以看到的所有内容。
您将在此处找到 API 的详尽说明:
http://msdn.microsoft.com/en-us/library/system.reflection.aspx
如果你不想浏览整个图书馆,这里是我制作的一个例子:
namespace Canvas
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod());
DiscreteMathOperations viola = new DiscreteMathOperations();
int resultOfSummation = 0;
resultOfSummation = viola.ConsecutiveIntegerSummation(1, 100);
Console.WriteLine(resultOfSummation);
}
}
public class DiscreteMathOperations
{
public int ConsecutiveIntegerSummation(int startingNumber, int endingNumber)
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod());
int result = 0;
result = (startingNumber * (endingNumber + 1)) / 2;
return result;
}
}
}
Run Code Online (Sandbox Code Playgroud)
此代码的输出将是:
Void Main<System.String[]> // Call to GetCurrentMethod() from Main.
Int32 ConsecutiveIntegerSummation<Int32, Int32> //Call from summation method.
50 // Result of summation.
Run Code Online (Sandbox Code Playgroud)
希望我能帮到你!
日航
| 归档时间: |
|
| 查看次数: |
90489 次 |
| 最近记录: |