如果我有一个名为MyProgram的类,是否有一种方法检索“MyProgram”作为字符串?
当前回答
最简单的方法是使用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
其他回答
在c# 6.0中,你可以使用操作符的名称:
nameof(MyProgram)
试试这个:
this.GetType().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 );
}
这可以用于泛型类
typeof (T)。的名字
我还想把这个吐出来。我认为@micahtan的发帖方式更可取。
typeof(MyProgram).Name
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和