如何将公共抽象类的子类化限制为同一程序集中的类型,从而允许将受保护的成员类型化为内部类型 [英] How to limit subclassing of public abstact class to types in same assembly and thus allow protected members typed to internal types

查看:14
本文介绍了如何将公共抽象类的子类化限制为同一程序集中的类型,从而允许将受保护的成员类型化为内部类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题类似于c#内部抽象类,如何将用法隐藏在外面,但我的动机不同.这是场景

This question is similar to c# internal abstract class, how to hide usage outside but my motiviation is different. Here is the scenario

我从以下几点开始:

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.

手头的问题是我如何(或者我可以吗?)告诉编译器只有与 PublicBaseClass 相同的程序集中的公共类可以从它继承,因此 _fieldA 不会暴露在程序集之外?

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

但那太丑了!

推荐答案

CLR 提供了 FamilyAndAssembly 可访问性,可以执行您想要的操作,但 C# 中没有使用它的语法.

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.

您也可以将 PublicBaseClass 的构造函数设为内部,这样只有您的程序集才能实例化它.这样,只有您的类可以继承它(即使类本身是公共的)

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)

这篇关于如何将公共抽象类的子类化限制为同一程序集中的类型,从而允许将受保护的成员类型化为内部类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆