Why can't we use a constructor with a parameter in derived classes

Why is this impossible? I get the following compiler error when instantiating "DerivedClass" with constructor parameter:

'GenericParameterizedConstructor.DerivedClass' does not contain a constructor that takes 1 argument

But calling a very similar method works.

Why?

class Program
{
    static void Main(string[] args)
    {
        // This one produces a compile error 
        // DerivedClass cls = new DerivedClass("Some value");

        // This one works;
        DerivedClass cls2 = new DerivedClass();
        cls2.SomeMethod("Some value");
    }
}


public class BaseClass<T>
{
    internal T Value;

    public BaseClass()
    {
    }

    public BaseClass(T value)
    {
        this.Value = value;
    }

    public void SomeMethod(T value)
    {
        this.Value = value;
    }
}

public class DerivedClass : BaseClass<String>
{
}
+1
source share
3 answers

Constructors are not inherited - it's that simple. DerivedClasscontains one constructor - an open constructor without parameters, provided by default by the compiler, because you did not specify any constructors.

, . , BaseClass .

DerivedClass, :

public class DerivedClass : BaseClass<String>
{
    public DerivedClass() : base()
    {
    }

    public DerivedClass(string value) : base(value)
    {
    }
}
+5

public class DerivedClass : BaseClass<String>
{
    public DerivedClass(string str) :base(str) {}
}
0

, , . . , , . , :

parentType(int foo) {...}
parentType(string foo) {...}

:

derivedType(string foo) {...}

new derivedType(7);? , new baseType(7);, "" , , derivedType, derivedType . ( ), .

By the way, there are several related problems with protected constructors. In some .net languages, including at least the current version of C #, if not an abstract type Foodefines a protected constructor, this constructor can only be used to instantiate derived types. In other languages, including the current vb.net, for code inside a derived type, you can call the protected constructor of the base type to create a new instance of the base type.

0
source

All Articles