c#获取自己的类名

如果我有一个类称为MyProgram,是否有一种方法检索“MyProgram”作为字符串?

545616 次浏览

试试这个:

this.GetType().Name

我还想把这个吐出来。我认为@micahtan发布的方式更可取。

typeof(MyProgram).Name

虽然micahtan的答案很好,但它在静态方法中不起作用。如果你想检索当前类型的名称,这个方法应该在任何地方都适用:

string className = MethodBase.GetCurrentMethod().DeclaringType.Name;

作为参考,如果您有从另一个类型继承的类型,您也可以使用

this.GetType().BaseType.Name

在c# 6.0中,你可以使用nameof操作符:

nameof(MyProgram)

使用这个

假设应用程序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();
}
}

this可以省略。所有你需要得到当前类名的是:

GetType().Name

获取Asp.net的当前类名

string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();

这可以用于泛型类

typeof (T)。的名字

最简单的方法是使用call name属性。但是,目前还没有返回调用方法的类名或名称空间的属性类。

看到:# EYZ0

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