简体   繁体   中英

How can I have both abstract and virtual methods in one class?

In the following parent class SqlStatement , how can I make Initialize() abstract but keep Execute() virtual ?

using System;
using System.Collections.Generic;

namespace TestSql28374
{
    class Program
    {
        static void Main(string[] args)
        {
            object item = new object();
            List<string> properties = new List<string>();

            SqlCreateStatement sqlCreateStatement = new SqlCreateStatement(properties);
            sqlCreateStatement.Execute();

            SqlInsertStatement sqlInsertStatement = new SqlInsertStatement(item, properties);
            sqlInsertStatement.Execute();

            Console.ReadLine();
        }
    }

    public class SqlStatement
    {
        protected List<string> properties;
        protected object item;
        protected string sql;

        public SqlStatement(List<string> properties) 
        {
            this.properties = properties;
        }

        protected virtual void Initialize() //should be abstract
        { }

        public virtual void Execute()
        {
            Console.WriteLine("Sending to database: " + sql);
        }
    }

    public class SqlCreateStatement : SqlStatement
    {

        public SqlCreateStatement(List<string> properties)
            : base(properties)
        {
            Initialize();
        }

        protected override void Initialize()
        {
            sql = "CREATE TABLE...";
        }
    }

    public class SqlInsertStatement : SqlStatement
    {
        public SqlInsertStatement(object item, List<string> properties)
            : base(properties)
        {
            this.item = item;

            Initialize();
        }

        protected override void Initialize()
        {
            sql = "INSERT INTO...";
        }
    }
}

使其成为抽象类

Can't you just declare it as abstract?

public abstract class SqlStatement
    {
        protected List<string> properties;
        protected object item;
        protected string sql;

        public SqlStatement(List<string> properties) 
        {
            this.properties = properties;
        }

        protected abstract void Initialize();

        public virtual void Execute()
        {
            Console.WriteLine("Sending to database: " + sql);
        }
    }

声明SqlStatement为抽象。

public abstract class SqlStatement {
...
protected abstract void Initialize(); //abstract
....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM