为什么我们不能在派生类中使用带参数的构造函数 [英] Why can't we use a constructor with parameter in derived classes

查看:324
本文介绍了为什么我们不能在派生类中使用带参数的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不可能?
使用constructor-parameter实例化DerivedClass时,得到以下编译器错误:



'GenericParameterizedConstructor.DerivedClass'不包含构造函数,



为什么?


$

b $ b

  class Program 
{
static void Main(string [] args)
{
//编译错误
// DerivedClass cls = new DerivedClass(Some value);

//这一个工作;
DerivedClass cls2 = new DerivedClass();
cls2.SomeMethod(Some value);
}
}


public class BaseClass< T>
{
内部T值;

public BaseClass()
{
}

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

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

public class DerivedClass:BaseClass< String>
{
}


解决方案

不是继承 - 它是那么简单。 DerivedClass 包含一个构造函数 - 由编译器默认提供的public无参构造函数,因为您没有指定任何构造函数。



请注意,这与泛型无关。 如果 BaseClass 不是通用的,你会看到同样的东西。



/ em>构造函数 DerivedClass 通过:

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

public DerivedClass(s​​tring value):base {
}
}


Why is this not possible? I get the following compiler-error when instantiating "DerivedClass" with a 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>
{
}

解决方案

Constructors aren't inherited - it's as simple as that. DerivedClass contains a single constructor - the public parameterless constructor provided by default by the compiler, because you haven't specified any constructors.

Note that this has nothing to do with generics. You'd see the same thing if BaseClass weren't generic.

It's easy to provide constructors for DerivedClass though:

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

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

这篇关于为什么我们不能在派生类中使用带参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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