Make field/method accessible only to derived classes within same assembly? [duplicate]

一曲冷凌霜 提交于 2019-12-11 07:30:28

问题


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.


回答1:


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; }
}



回答2:


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>...")]



回答3:


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.



来源:https://stackoverflow.com/questions/4271548/make-field-method-accessible-only-to-derived-classes-within-same-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!