如果我有一个名为MyProgram的类,是否有一种方法检索“MyProgram”作为字符串?
当前回答
如果你在派生类中需要这个,你可以把这个代码放在基类中:
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();
}
}
其他回答
试试这个:
this.GetType().Name
我还想把这个吐出来。我认为@micahtan的发帖方式更可取。
typeof(MyProgram).Name
最简单的方法是使用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
这个可以省略。所有你需要得到当前类名的是:
GetType().Name
虽然micahtan的答案很好,但它在静态方法中不起作用。如果你想检索当前类型的名称,这个方法应该在任何地方都适用:
string className = MethodBase.GetCurrentMethod().DeclaringType.Name;
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因