wpf 获取当前类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38838825/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:54:08  来源:igfitidea点击:

Get Current Class Name

c#wpf

提问by pixel

In Android, if I need to get name of current class, i can do something like:

在 Android 中,如果我需要获取当前类的名称,我可以执行以下操作:

private final _TAG = DummyActivity.this.getClass().getSimpleName();

this would return "DummyActivity"

这将返回“DummyActivity”

I want to do same in C# WPF app code-behind. How do I get the name of current class?

我想在 C# WPF 应用程序代码隐藏中做同样的事情。如何获取当前班级的名称?

this.GetType().Name; //this works only on instances of a class 

Looks like the only option is to hard-code it in C# like this:

看起来唯一的选择是在 C# 中硬编码它,如下所示:

private const string _TAG = "DummyWindow";

回答by 123 456 789 0

You can use either the following:

您可以使用以下任一方法:

1.) typeof(T).Name(Vanilla .NET way)

1.) typeof(T).Name香草.NET方式

2.) nameof(T)(C#6 only)

2.) nameof(T)仅限 C#6

回答by Yacoub Massad

You can do it like this in C#:

你可以在 C# 中这样做:

private static string _TAG = MethodBase.GetCurrentMethod().DeclaringType.Name;

This will work because initializing this field actually happens in the static constructor. I.e., MethodBase.GetCurrentMethod()returns the static constructor of the class.

这将起作用,因为初始化此字段实际上发生在静态构造函数中。即,MethodBase.GetCurrentMethod()返回类的静态构造函数。

回答by H.B.

An instancewould exactly be "current", the concept does not make much sense otherwise. If you just want the name of a known typethat would be typeof(Class).Name.

一个实例恰好是“当前”的,否则这个概念没有多大意义。如果你只想要一个已知类型的名称,那就是typeof(Class).Name.

回答by Roman Marusyk

Try

尝试

typeof(DummyActivity).Name

回答by Joseph Evensen

nameof(DummyActivity) == new DummyActivity().GetType().Name

回答by CoolBots

Exact same statement in C# 6:

C# 6 中完全相同的语句:

private static readonly string _TAG = nameof(DummyActivity);