5

尝试在公共类中创建受保护内部类的受保护内部成员会导致以下问题:

可访问性不一致:字段类型“what.Class1.ProtectedInternalClass”的可访问性低于字段“what.Class1.SomeDataProvider.data”

据我所知,可访问性应该是等效的。

我错在哪里?

起源类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace what
{
    public class Class1
    {
        // This class cannot be modified, is only 
        // here to produce a complete example.
        public class PublicClass
        {
            public PublicClass() { }
        }

        protected internal class ProtectedInternalClass : PublicClass
        {
            public ProtectedInternalClass() { }

            public void SomeExtraFunction() { }
        }

        public class SomeDataProvider
        {
            public int AnInterestingValue;
            public int AnotherInterestingValue;

            protected internal ProtectedInternalClass data; //<--- Occurs here.
            public PublicClass Data { get { return data; } }
        }


        public static SomeDataProvider RetrieveProvider()
        {
            SomeDataProvider provider = new SomeDataProvider();

            provider.data = new ProtectedInternalClass();
            provider.data.SomeExtraFunction();

            return provider;
        }

    }
}

验证受保护和内部属性,相同的程序集:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace what
{
    public class Class2 : Class1
    {
        public Class2()
        {
            var pi = new ProtectedInternalClass();

            var provider = new SomeDataProvider();
            provider.data = pi;
        }
        // no errors here
    }

    public class Class3
    {
        public Class3()
        {
            var pi = new Class1.ProtectedInternalClass();

            var provider = new Class1.SomeDataProvider();
            provider.data = pi;
        }
        // no errors here
    }
}

验证受保护和内部属性,不同的程序集:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace some_other_assembly
{
    public class Class4 : what.Class1
    {
        public Class4()
        {
            var pi = new ProtectedInternalClass();

            var provider = new SomeDataProvider();
            provider.data = pi;
        }
        // no errors here
    }

    public class Class5
    {
        public Class5()
        {
            var pi = new what.Class1.ProtectedInternalClass(); // <--- Inaccessible due to protection level, as it should be.

            var provider = new what.Class1.SomeDataProvider();
            provider.data = pi; // <--- Intellisense implies inaccessible, but not indicated via error.
        }
    }
}
4

1 回答 1

3

适用于不同的protected类,这可以通过

class Derived : what.Class1.SomeDataProvider // note: Derived is not a nested class
{
    public void f()
    {
        var data = this.data;
    }
}

在不同的程序集中。

this.data必须是可访问的,因为该类派生自SomeDataProvider. 它的类型 ,ProtectedInternalClass是不可访问的,因为该类不是派生自Class1

于 2013-09-12T14:49:52.153 回答