C# 获取自己的类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2113069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# getting its own class name
提问by deltanovember
If I have a class called MyProgram
, is there a way of retrieving "MyProgram" as a string?
如果我有一个名为 的类MyProgram
,有没有办法将“ MyProgram”作为字符串检索?
采纳答案by micahtan
Try this:
尝试这个:
this.GetType().Name
回答by ChaosPandion
回答by Thomas Levesque
Although micahtan's answer is good, it won't work in a static method. If you want to retrieve the name of the current type, this one should work everywhere:
尽管 micahtan 的回答很好,但它在静态方法中不起作用。如果你想检索当前类型的名称,这个应该可以在任何地方使用:
string className = MethodBase.GetCurrentMethod().DeclaringType.Name;
回答by mikeschuld
For reference, if you have a type that inherits from another you can also use
作为参考,如果您有一个从另一个继承的类型,您也可以使用
this.GetType().BaseType.Name
回答by Cyanfish
回答by Harshal Doshi Jain
Use this
用这个
Let say Application Test.exeis running and function is foo()in form1[basically it is class form1], then above code will generate below response.
让说应用将Test.exe正在运行,并且功能是FOO()在Form1中[基本上它是Form1类],然后上面的代码会产生下面的反应。
string s1 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
This will return .
这将返回。
s1 = "TEST.form1"
for function name:
对于函数名称:
string s1 = System.Reflection.MethodBase.GetCurrentMethod().Name;
will return
将返回
s1 = foo
Note if you want to use this in exception use :
请注意,如果您想在异常使用中使用它:
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace );
}
回答by bafsar
If you need this in derived classes, you can put that code in the base class:
如果您需要在派生类中使用它,您可以将该代码放在基类中:
protected string GetThisClassName() { return this.GetType().Name; }
Then, you can reach the name in the derived class. Returns derived class name. Of course, when using the new keyword "nameof", there will be no need like this variety acts.
然后,您可以访问派生类中的名称。返回派生类名。当然,当使用新关键字“nameof”时,就不需要像这样的变种行为了。
Besides you can define this:
此外你可以定义这个:
public static class Extension
{
public static string NameOf(this object o)
{
return o.GetType().Name;
}
}
And then use like this:
然后像这样使用:
public class MyProgram
{
string thisClassName;
public MyProgram()
{
this.thisClassName = this.NameOf();
}
}
回答by Mikael Engver
this
can be omitted. All you need to get the current class name is:
this
可以省略。获取当前类名所需的全部内容是:
GetType().Name
回答by Abbas ali
Get Current class name of Asp.net
获取 Asp.net 的当前类名
string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();