如何在一个类中同时拥有抽象方法和虚拟方法?
在下面的父类SqlStatement中,如何使Initialize() 抽象但保留Execute() 虚拟?
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...";
}
}
}
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...";
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使其成为一个抽象类
Make it an abstract class
你不能把它声明为抽象吗?
Can't you just declare it as abstract?
将 SqlStatement 声明为抽象。
Declare SqlStatement as abstract.