Dynamically change namespace in C#

末鹿安然 提交于 2021-02-10 12:12:14

问题


I want to do something like this. If DEBUG is defined then the namespace is Test, or the namespace is TestB. See the sample code bellow. Can I do that or you have better ideas to achieve this? Thanks in advance!

# if DEBUG
     [SomekindofAttribute(Namespace = "Test")]
 #endif
namespace TestB
 {

     public class Program
     {}
 }

回答1:


You can do this:

#if DEBUG
namespace TestB
#else
namespace Test
#endif
{
    public class Program { }
}

Though this looks like a very bad idea. Everything using Program would have to do the same preprocessor directives for their using declarations, too.




回答2:


Why not adding condition into the namespace declaration itself?
If I understand your question correctly, then you can use code below.

#if DEBUG
namespace Test
#else
namespace TestB
#endif
{
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine(new Program().GetType().FullName);
            Console.ReadLine();
        }
    }
}

Please confirm is this is what you want.



来源:https://stackoverflow.com/questions/40414351/dynamically-change-namespace-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!