如果我有一个名为MyProgram的类,是否有一种方法检索“MyProgram”作为字符串?
虽然micahtan的答案很好,但它在静态方法中不起作用。如果你想检索当前类型的名称,这个方法应该在任何地方都适用:
string className = MethodBase.GetCurrentMethod().DeclaringType.Name;
使用这个
假设应用程序Test.exe正在运行,函数是form1中的foo()[基本上是类form1],然后上面的代码将生成下面的响应。
string s1 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
这将返回。
s1 = "TEST.form1"
函数名:
string s1 = System.Reflection.MethodBase.GetCurrentMethod().Name;
将返回
s1 = foo
注意,如果你想在异常使用中使用这个:
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace );
}
如果你在派生类中需要这个,你可以把这个代码放在基类中:
protected string GetThisClassName() { return this.GetType().Name; }
然后,您可以在派生类中找到该名称。返回派生类名。当然,当使用新的关键字“nameof”时,就不需要这样的变化行为了。
此外,你可以这样定义:
public static class Extension
{
public static string NameOf(this object o)
{
return o.GetType().Name;
}
}
然后像这样使用:
public class MyProgram
{
string thisClassName;
public MyProgram()
{
this.thisClassName = this.NameOf();
}
}
获取Asp.net的当前类名
string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();
最简单的方法是使用call name属性。但是,目前还没有返回调用方法的类名或名称空间的属性类。
看:CallerMemberNameAttributeClass
public void DoProcessing()
{
TraceMessage("Something happened.");
}
public void TraceMessage(string message,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
System.Diagnostics.Trace.WriteLine("message: " + message);
System.Diagnostics.Trace.WriteLine("member name: " + memberName);
System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
}
// Sample Output:
// message: Something happened.
// member name: DoProcessing
// source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs
// source line number: 31
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和