Make field/method accessible only to derived class

2019-08-11 00:05发布

This question already has an answer here:

On a public class in C# is there a way to make a field/method accessible only to derived classes within the same assembly?

From what I understand protected internal in C# means the same as protected or internal (ie accessible to derived classes or classes from the same assembly), which is not what I need.

3条回答
爷、活的狠高调
2楼-- · 2019-08-11 00:27

If the class is internal, there will be no way to sub-class it outside of the assembly. Make the fields/methods protected and you're good to go.

If the class must be public, use an internal sub-class everywhere within your assembly.

查看更多
一纸荒年 Trace。
3楼-- · 2019-08-11 00:34

You can't prevent a class from an external assembly from compiling a call to it, but you can force an exception to occur at runtime if they do by putting this attribute on your protected member:

   [System.Security.Permissions.StrongNameIdentityPermission(
    System.Security.Permissions.SecurityAction.LinkDemand, 
    PublicKey = "...<Your assembly's full public key>...")]
查看更多
做自己的国王
4楼-- · 2019-08-11 00:36

What if you removed the "internal" only fields/methods from the public class to an internal class. Then all of the classes in that assembly could derive from the internal class:

public abstract class MyClass
{
    public string Name { get; set; }
}

// Only classes in this assembly can derive from this class
internal abstract class InternalClass : MyClass
{
    protected string Other { get; set; }
}
查看更多
登录 后发表回答