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 t开发者_StackOverflowo use something like this FileDownloader.Name(), where FileDownloader is name of the class.
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?
Sure:
var name = typeof(FileDownloader).Name;
use the typeof operator:
typeof ( FileDownloader).Name
Try typeof(YourClass).name. This should expose the name of your class
In 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... :)
精彩评论