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