在抽象类中使用构造函数

时间:2014-07-22 17:58:44

标签: c# c#-4.0 constructor abstract-class

我有一个课程如下:

public abstract class cDBBase
{
     public cDBBase()
     {
         some codes
      }
      Some codes;
 }

我有另一个班级

public class cSQL : cDBBase
{
     public void cSQL()
     {
         Some codes;
     }
}

为什么在子类构造函数中出现错误“成员名称与其封闭类型的名称不同”?

以下是完整的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Uploader
{
    public abstract class cDBBaseClass
    {
        public string ServerName { get; set; }
        public string DBName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string ConnString;

        public cDBBaseClass(string serverName, string dBName, string userName, string password)
        {
            ServerName = serverName;
            DBName = dBName;
            UserName = userName;
            Password = password;
        }

        public abstract string SetConnString();

        public abstract void SetConn();
    }
}

和子类

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;


namespace Uploader.Classes
{
    public class cSQL:cDBBaseClass
    {
        private SqlConnection Conn = new SqlConnection();

        public cSQL()
        {
            SetConnString();
            SetConn();
        }


        public override string SetConnString()
        {
            return "data source = " + this.ServerName +
                   "; database = " + this.DBName +
                   "; User ID = " + this.UserName +
                   "; Password = " + this.Password;
        }

        public override void SetConn()
        {
            Conn.ConnectionString = this.ConnString;
        }

        public SqlDataReader ExecSQL(string Query)
        {
            using (SqlConnection Conn = new SqlConnection(SetConnString()))
            {
                Conn.Open();   
                SqlCommand cmd = new SqlCommand(Query , Conn);
                return cmd.ExecuteReader();
            }
        }


        public SqlDataReader ExecStoredProcedure(string SPName)
        {
            using (SqlConnection Conn = new SqlConnection(SetConnString()))
            {
                Conn.Open();
                SqlCommand cmd = new SqlCommand(SPName, Conn);
                cmd.CommandType = CommandType.StoredProcedure;
                return cmd.ExecuteReader();
            }
        }


    }
}

2 个答案:

答案 0 :(得分:6)

您正在定义一个方法cSQL,其名称与其所包含的类完全相同。您不能这样做。你的意思是建造一个构造函数吗?只需删除void

答案 1 :(得分:1)

确实修复了你的原始问题,但为了修复你的其他问题,你的类必须接受与基类相同的参数,并将它们传递给它:

public class cSQL : cDBBaseClass
{
    private SqlConnection Conn = new SqlConnection();

    public cSQL(string serverName, string dBName, string userName, string password)
        : base(serverName, dBName, userName, password)
    {
        SetConnString();
        SetConn();
    }

    ...