c# - 仅将构造函数公开给基类,可能吗?

标签 c# generics inheritance visibility access-modifiers

public class Base<S>
{
    public static Derived<S, T> Create<T>()
    {
        return new Derived<S, T>(); //if not public, I wont get it here.
    }
}

public class Derived<S, T> : Base<S>
{
    public Derived() //the problem, dont want it public
    {

    }
}

这是我得到的基本结构。

要求:

1) 我不想要 Derived<,> 的实例调用 Derived<,> 构建类,无论是通过构造函数还是静态方法。我希望它只能通过 Base<> 创建.所以这是出来的:

public class Derived<S, T> : Base<S>
{
    Derived()
    {

    }

    public static Derived<S, T> Create()
    {
        return new Derived<S, T>();
    }
}

2) Derived<,>类本身必须是公共(public)的(这意味着我不能在 Derived<,> 内部嵌套 Base<>)。只有这样我才能返回 Derived<,>来自静态Create Base<> 中的方法.

这可能吗?

最佳答案

您可以使派生类的构造函数internal,如

public class Base<S>
{
    public static Derived<S, T> Create<T>()  // visible externally
    {
        return new Derived<S, T>(); 
    }
}

public class Derived<S, T> : Base<S>
{
    internal Derived() // not visible outside the current assembly
    {

    }
}

关于c# - 仅将构造函数公开给基类,可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16093448/

相关文章:

c# - 使用 DTO 和 WPF 时是否需要实现 INotifyPropertyChanged?

c# - 带有 TextBlock 和复选框的 XAML ToggleButton

c++ - 为什么我调用mem_fun_ref会有 "no matching function"?

c# - 在 c++/c# 中从哪里开始抓取/爬行?

c# - 模拟接口(interface)的特定类实例

typescript - 具有通用叶包装器的可重用模型特定树结构

c# - 方法中的泛型,c#

Java Compiler 接受泛型方法引用,但在作为变量传递时不接受

ios - ios中继承UIViewController

python-3.x - __new__、__init__ 和元类(和父类(super class))