如何在一个类中同时使用抽象和虚拟方法?

时间:2009-12-04 14:05:23

标签: c# oop virtual abstract-class

在以下父类 SqlStatement 中,如何使初始化() 抽象,但保持执行() 虚拟

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...";
        }
    }
}

4 个答案:

答案 0 :(得分:9)

将其设为抽象类

答案 1 :(得分:6)

你难道不能把它宣布为抽象吗?

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);
        }
    }

答案 2 :(得分:3)

将SqlStatement声明为abstract。

答案 3 :(得分:1)

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