简体   繁体   English

如何在不实例化对象或使用静态方法的情况下获取类的名称?

[英]How to get the name of the class without instantiating object or having a static method?

I hate to see the name of the class used as a string parameter like "FileDownloader" in the code, and I would like to use something like this FileDownloader.Name(), where FileDownloader is name of the class. 我讨厌在代码中看到用作字符串参数的类的名称,如“FileDownloader”,我想使用类似FileDownloader.Name()的东西,其中FileDownloader是类的名称。
Only problem is that I can't find out how to do that without instantiating object or creating a static method... 唯一的问题是我无法在不实例化对象或创建静态方法的情况下找到如何做到这一点......

Is there a way to get a class name in .net without having the object instance and without creating a static method that returns the name of the class? 有没有办法在.net中获取类名而不使用对象实例并且不创建返回类名称的静态方法?

当然:

var name = typeof(FileDownloader).Name;

使用typeof运算符:

typeof ( FileDownloader).Name

Try typeof(YourClass).name. 尝试typeof(YourClass).name。 This should expose the name of your class 这应该公开您的类的名称

In VB.Net: 在VB.Net中:

Dim sf As StackFrame = New StackFrame()
Dim mb As MethodBase = sf.GetMethod()
Dim className = mb.DeclaringType.Name

There you go. 你去吧 Totally dynamic. 完全动态。 Just be careful about refactoring... If you move it to another class, the class name will change... :) 注意重构......如果你把它移到另一个类,类名会改变...... :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在运行时获取静态类的方法名称? - How to get method name of a static class in runtime? C#使用反射调用公共非静态方法而不实例化其类 - C# calling a public non-static method using reflection without instantiating its class 在不实例化类的情况下,在不同类中访问方法相同名称空间 - Accessing Method in different class Same name space without instantiating the class Reference Only 在基类中执行静态方法时,如何获取派生类的类名? - How to get the class name of a derived class when executing a static method in the base class? 是否静态引用了Class的“ this”实例,而没有实例化Class的实例? - Static reference to 'this' instance of a Class without ever instantiating an instance of the Class? 获取PropertyInfo的默认值而不实例化对象? - Get the default value of a PropertyInfo without instantiating the object? 实例化类和使用其方法并使方法静态并在不实例化类的情况下使用它们之间有什么区别 - What are the differences between instantiating a class and using its methods and making methods static and using them without instantiating the class 我如何声明一个名称为static的类 - How can i declare a class having name static 在多个线程中实例化非静态类时出现对象引用错误 - Object reference error while instantiating non static class in multiple threads 我如何使用一个类而不实例化它? - how do i use a class without instantiating it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM