Base Class Doesn't Contain Parameterless Constructor?

http://stackoverflow.com/questions/7689742/base-class-doesnt-contain-parameterless-constructor

#region Assembly System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Data.Entity.dll
#endregion

ObjectContext类所处的命名空间System.Data.Objects

public partial class DB_COMAPEntities : ObjectContext

{

}

上面的类,无法通过编译,提示说,父类(ObjectContext)没有无参构造函数

 

DB_COMAPEntities 子类默认有一个无参构造函数,这个默认的无参构造函数去调用父类的无参构造函数。

而父类ObjectContext恰好没有无参构造函数,所以出错了。

 

 

解决方法:

显示指定调用的父类的有参构造函数,传递给父类有参构造函数的参数,是写死的常量。

public partial class DB_COMAPEntities : ObjectContext
    {
        public DB_COMAPEntities() : base("name=DB_COMAPEntities", "DB_COMAPEntities")
        { }
    }

 

 

 

http://stackoverflow.com/questions/7689742/base-class-doesnt-contain-parameterless-constructor

class A
{
    public A(int x, int y)
    {
        // do something
    }
}

class A2 : A
{
    public A2() : base(1, 5)
    {
        // do something
    }

    public A2(int x, int y) : base(x, y)
    {
        // do something
    }

    // This would not compile:
    public A2(int x, int y)
    {
        // the compiler will look for a constructor A(), which doesn't exist
    }
}

In class A2, you need to make sure that all your constructors call the base class constructor with parameters.

Otherwise, the compiler will assume you want to use the parameterless base class constructor to construct the A object on which your A2 object is based.

 

 

总结:

在父类没有无参构造函数的时候,子类的构造函数,必须显示指定如何调用父类的有参构造函数

 

你可能感兴趣的:(Base Class Doesn't Contain Parameterless Constructor?)