简体   繁体   中英

C# protected internal method with internal return type?

Does this mean protected method cannot be internal in a public type?

internal class InternalReturnType
{
}

public class PublicTypeWithProtectedMethod
{
    //build succeeded when I remove `protected`
    internal protected InternalReturnType GetValue()
    {
        return new InternalReturnType();
    }
}

public sealed class PublicTypeWithPublicMethod : PublicTypeWithProtectedMethod
{
    public void Print()
    {
        var value = base.GetValue();
    }
}

internal protected means that the member is accessible from either the declaring assembly or from any derived type in any assembly. Since InternalReturnType is marked as internal it will only be accessible from the declaring assembly. This is why the compiler complains as it can't honor both restrictions, if you can access GetValue from any derived type in any assembly, you should be able to access InternalReturnType from any assembly, but it is marked as internal so it shouldn't be accessible from any assembly. You can either remove protected from the member or make InternalReturnType public.

Note Depending on what you are trying to do, you should have a look at private protected (available on C# 7.2). This will allow access in derived types only within the assembly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM