本文介绍了如何限制公共abstact类的子类在同一个程序集中的类型,从而使保护成员类型为内部类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 此问题是类似的 C#内部抽象类,如何隐藏使用外,但我的motiviation是不同的。下面是该方案 我开始与以下内容: 内部类InternalTypeA {...} 公共类PublicClass {私人只读InternalTypeA _fieldA; :} 以上编译罚款。但后来我决定,我要提取一个基类,试着写了以下内容: 公共抽象类PublicBaseClass {保护只读InternalTypeA _fieldA; :} 因而问题,受保护的成员是集外可见,但是一个内部类型,所以不会进行编译。 目前的问题是,如何我(或者可以吗? )告诉唯一的公共类在同一个组件,PublicBaseClass可能继承它,因此_fieldA不会组装之外expossed编译器? 或者有另一种方式做我想做的事情,有一个公共的超类以及一组都在相同的组装和在共同的(受保护)代码? $ b使用内部类型从装配公共基类 $ b 到目前为止,我有唯一的想法是这样的: 公共抽象类PublicBaseClass {私人只读InternalTypeA _fieldA; 保护对象FIELDA {{返回_fieldA; }} :} 公共类SubClass1:PublicBaseClass {私人InternalTypeA _fieldA {{返回(InternalTypeA) FIELDA; }} } 公共类SubClass2:PublicBaseClass {私人InternalTypeA _fieldA {{返回(InternalTypeA)FIELDA; }} } 但是,这是丑陋的! 解决方案 CLR提供一个FamilyAndAssembly辅助功能,这将做你想要的,但没有在C#的语法来使用它。 解决方法是把这些变量场内部,你会在你的装配信任的代码不会不适当地访问它。 您也可以PublicBaseClass内部的构造,所以只有你的组件可进行实例化。这样,只有你的类可以继承了它(即使类本身是公共的) This question is similar to c# internal abstract class, how to hide usage outside but my motiviation is different. Here is the scenarioI started with the following:internal class InternalTypeA {...}public class PublicClass{ private readonly InternalTypeA _fieldA; ...}The above compiles fine. But then I decided that I should extract a base class and tried to write the following:public abstract class PublicBaseClass{ protected readonly InternalTypeA _fieldA; ...}And thus the problem, the protected member is visible outside the assembly but is of an internal type, so it won't compile.The issue at hand is how to I (or can I?) tell the compiler that only public classes in the same assembly as PublicBaseClass may inherit from it and therefore _fieldA will not be expossed outside of the assembly?Or is there another way to do what I want to do, have a public super class and a set of public base classes that are all in the same assembly and use internal types from that assembly in their common ("protected") code?The only idea I have had so far is the following:public abstract class PublicBaseClass{ private readonly InternalTypeA _fieldA; protected object FieldA { get { return _fieldA; } } ...}public class SubClass1 : PublicBaseClass{ private InternalTypeA _fieldA { get { return (InternalTypeA)FieldA; } } }public class SubClass2 : PublicBaseClass{ private InternalTypeA _fieldA { get { return (InternalTypeA)FieldA; } } }But that is UGLY! 解决方案 The CLR provides a FamilyAndAssembly accessibility which will do what you want, but there isn't the syntax in C# to use it.The workaround is to make the variable field internal, and you'll have to trust the code in your assembly to not access it inappropriately.You can also make the constructor of PublicBaseClass internal, so only your assembly can instantiate it. That way, only your classes can inherit off it (even if the class itself is public) 这篇关于如何限制公共abstact类的子类在同一个程序集中的类型,从而使保护成员类型为内部类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-10 06:03