Public and Internal members in an Internal class?

后端 未结 5 797
暗喜
暗喜 2020-12-25 11:00

Ok, so this may be a bit of a silly question, and there\'s certainly the obvious answer, but I was curious if I\'ve missed any subtleties here.

Is there any differen

相关标签:
5条回答
  • 2020-12-25 11:02

    If it comes to reflection it matters if the member is public or not:

    For example you even could pass a nested private class to a WPF binding and the binding would work against the public properties just as usual.

    0 讨论(0)
  • 2020-12-25 11:03

    Just faced with another example where there is difference between those two, when used from XAML in WPF.

    XAML:

    <Button Tag="{x:Static vm:Foo+Bar.e1}" />
    

    Code with internal enum compiles successfully:

    internal class Foo
    {
        internal enum Bar
        {
            e1,
            e2,
        }
    }
    

    But surprisingly changing it to public results in error:

    internal class Foo
    {
        public enum Bar
        {
            e1,
            e2,
        }
    }
    

    The last example produces compilation error:

    error MC3064: Only public or internal classes can be used within markup. 'Bar' type is not public or internal.

    Unfortunately, I can't explain what's wrong with public in this case. My guess is "just because WPF works that way". Just change modifier of the nested class to internal to get rid of error.

    0 讨论(0)
  • 2020-12-25 11:18

    Consider this case:

    public interface IBar { void Bar(); }
    internal class C : IBar
    {
        public void Bar() { }
    }
    

    Here C.Bar cannot be marked as internal; doing so is an error because C.Bar can be accessed by a caller of D.GetBar():

    public class D
    {
        public static IBar GetBar() { return new C(); } 
    }
    
    0 讨论(0)
  • 2020-12-25 11:21

    A public member is still just internal when in an internal class.

    From MSDN:

    The accessibility of a member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal type has only internal accessibility

    Think of it this way, I would access a public property on....? A class I can't see? :)

    Eric's answer is very important in this case, if it's exposed via an interface and not directly it does make a difference, just depends if you're in that situation with the member you're dealing with.

    0 讨论(0)
  • 2020-12-25 11:21

    public members of an internal class can override public members of public base classes and, therefore, be a little more exposed... if indirectly.

    0 讨论(0)
提交回复
热议问题