Partial class in different namespaces

前端 未结 6 659
再見小時候
再見小時候 2020-11-30 09:50

Can I create partial class in different namespaces? Will it work correct? e.x.:

class1.cs

namespace name1
{
    public partial class Foo
    {
               


        
6条回答
  •  伪装坚强ぢ
    2020-11-30 10:25

    Also, for static classes you can implement something like this with the help of fresh C# 6.0 using static feature.

    Consider:

    namespace SomeLogic1
    {
        public static class Util
        {
            public static int Bar1()
            {
                return 1;
            }
        }
    }
    
    namespace SomeLogic2
    {
        public static class Util
        {
            public static int Bar2()
            {
                return 2;
            }
        }
    }
    
    namespace GeneralStuff
    {
        using SomeLogic1;
        using SomeLogic2;
    
        public class MainClass
        {
            public MainClass()
            {
                // Error CS0104
                // 'Util' is an ambiguous reference between 'SomeLogic1.Util' and 'SomeLogic2.Util'
                var result = Util.Bar1() + Util.Bar2(); 
            }
        }
    }  
    

    Right, that does not compile, the error message is clear. To fix the situation you can directly specify namespaces (but you don't want this as far as I understand):

    namespace GeneralStuff
    {
        public class MainClass
        {
            public MainClass()
            {
                var result = SomeLogic1.Util.Bar1() + SomeLogic2.Util.Bar2(); 
            }
        }
    }
    

    OR you can apply using static feature this way:

    namespace GeneralStuff
    {
        using static SomeLogic1.Util;
        using static SomeLogic2.Util;
    
        public class MainClass
        {
            public MainClass()
            {
                var result = Bar1() + Bar2(); 
            }
        }
    }
    

    Perhaps it is ok to do this for some helper/utils classes. But partial classes are not the way, as other have noticed.

提交回复
热议问题