1

我有一个具有公共构造函数的基类。

基类不是密封的,也不是抽象的。

我希望密封一个构造函数。这可能吗?

我当前的尝试导致语法错误,说构造函数不能被密封。

public sealed MyBase(string someParam)

额外的:

我希望能够直接实例化基类并访问密封的构造函数。派生类不能通过派生构造函数使用该构造函数。例如

public MyDerived() : base(string cant_access_my_sealed_constructor)
4

3 回答 3

9

You can't do that. If the constructor is public, you can call it from constructors of derived classes. But you can do something close – you can have a private constructor and a public static method that calls it:

class MyBase
{
    private MyBase(string someParam)
    {
        // some code
    }

    public static MyBase Create(string someParam)
    {
        return new MyBase(someParam);
    }

    protected MyBase() // or some other protected or public constructor
    { }
}

class MyDerived : MyBase
{
    public MyDerived()
        : base("foo") // won't compile, as requested
    { }
}
于 2011-09-30T00:26:48.690 回答
6

所有构造函数都是“密封的”,因为它们不能被“覆盖”。它们只能从子类的构造函数中调用。

如果您希望防止子类具有具有相同签名的构造函数,则无法做到这一点。

根据您添加到帖子中的其他信息,听起来您想要做的就是将您的构造函数设为私有,正如 Kyle 建议的那样。这将阻止子类调用构造函数,但不会阻止它采用相同类型的参数:

public class Foo
{
    private Foo(string s){
    }
    // Allowed
    public Foo() : this("hello") {
    }
}

public class Bar : Foo
{
    // Allowed
    public Bar(string s) : base(){
    }
    // Not allowed
    public Bar(string s) : base(s){
    }
}
于 2011-09-30T00:07:51.860 回答
2

如果要防止构造函数被继承的类调用,只需将其标记为私有即可。

子类不继承构造函数,如果需要,您必须显式调用基本构造函数。

当子类的实例被实例化时,此代码将调用基类的无参数构造函数。没有它,在创建子类的新实例时将不会调用基类的构造函数。

public class A
{
    public A() 
    {
    }
}

public class B : A
{
    public B() 
        : base() 
    {
    }
}
于 2011-09-30T00:07:13.607 回答