如何使构造函数只能由基类访问? [英] How do I make a constructor only accessible by base class?

查看:93
本文介绍了如何使构造函数只能由基类访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想要一个只能从子类访问的构造函数,则可以在构造函数中使用受保护的关键字。

If I want a constructor that is only accessible from child classes I can use the protected key word in the constructor.

现在我要相反。

我的子类应该有一个可由其基类访问但不能从其他任何类访问的构造函数。

My child class should have an constructor that can be accessed by its base class but not from any other class.

这甚至可能吗?

这是我当前的代码。问题是子类具有公共构造函数。

This is my current code. the problem is that the child classes have a public constructor.

public abstract class BaseClass
{
    public static BaseClass CreateInstance(DataTable dataTable)
    {
        return new Child1(dataTable);
    }
    public static BaseClass CreateInstance(DataSet dataSet)
    {
        return new Child2(dataSet);
    }
}

public class Child1 : BaseClass
{
    public Child1(DataTable dataTable)
    {
    }
}

public class Child2 : BaseClass
{
    public Child2(DataSet dataSet)
    {
    }
}


推荐答案

我认为您有两种选择:


  1. 使子构造函数成为内部。这意味着可以从同一程序集中的所有类型访问它,但是在大多数情况下应该足够。

  2. 使子类嵌套在基类中:

  1. Make the child constructor internal. This means it will be accessible from all types in the same assembly, but that should be enough in most cases.
  2. Make the child classes nested in the base class:

public abstract class BaseClass
{
    public static BaseClass CreateInstance(DataTable dataTable)
    {
        return new Child1(dataTable);
    }

    private class Child1 : BaseClass
    {
        public Child1(DataTable dataTable)
        {
        }
    }
}

这样, BaseClass 可以使用构造函数,但没有其他外部类型可以做到这一点(甚至看不到子类)。

This way, BaseClass can use the constructor, but no other outside type can do that (or even see the child class).

这篇关于如何使构造函数只能由基类访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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