【发布时间】:2011-03-22 05:07:29
【问题描述】:
在 C# 中,有没有返回当前类/方法名的函数?
【问题讨论】:
-
@zerkms : 错误处理/记录。
-
所有这些都将在堆栈跟踪中。您可能不需要以编程方式访问它。
-
@John:“可能”对我来说不够好。
-
约翰可能错了。
标签: c#
在 C# 中,有没有返回当前类/方法名的函数?
【问题讨论】:
标签: c#
当前类名:
this.GetType().Name;
当前方法名:
using System.Reflection;
// ...
MethodBase.GetCurrentMethod().Name;
由于您将其用于日志记录,因此您可能也有兴趣获取current stack trace。
【讨论】:
this.GetType().Name; 静态方法的当前类名:System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType
【讨论】:
我将上面的示例稍微更改为这段工作示例代码:
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
}
}
}
输出:
Program.FooBar enter
Program.FooBar leave
【讨论】:
是的! 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;
}
}
}
这段代码的输出将是:
Void Main<System.String[]> // Call to GetCurrentMethod() from Main.
Int32 ConsecutiveIntegerSummation<Int32, Int32> //Call from summation method.
50 // Result of summation.
希望能帮到你!
日航
【讨论】:
你可以获取当前的类名,但是我无论如何也想不到获取当前的方法名。但是,可以获取当前方法的名称。
string className = this.GetType().FullName;
System.Reflection.MethodInfo[] methods = this.GetType().GetMethods();
foreach (var method in methods)
Console.WriteLine(method.Name);
【讨论】: