How can I retrieve the namespace to a string C#

后端 未结 9 1007
一向
一向 2020-12-15 02:38

I am writing a program which needs the namespace of the program but I cant seem to figure out how to retrieve it. I would like the end result to be in a string.

I wa

9条回答
  •  长情又很酷
    2020-12-15 03:01

    To add to all the answers.

    Since C# 6.0 there is the nameof keyword.

    string name = nameof(MyNamespace);
    

    This has several advantages:

    1. The name is resolved at compile-time
    2. The name will change when refactoring the namespace
    3. It is syntax checked, so the name must exist
    4. cleaner code

    Note: This doesn't give the full namespace though. In this case, name will be equal to Bar:

    namespace Foo.Bar
    {
       string name = nameof(Foo.Bar);
    }
    

提交回复
热议问题