ちょーしぶっこいてC#版:
using System;
namespace DB {
// 式
public abstract class Exp {
public static Exp operator&(Exp lhs, Exp rhs)
{ return new BinaryOp("AND", lhs, rhs); }
public static Exp operator|(Exp lhs, Exp rhs)
{ return new BinaryOp("OR" , lhs, rhs); }
public static Exp operator==(Exp lhs, Exp rhs)
{ return new BinaryOp("=" , lhs, rhs); }
public static Exp operator!=(Exp lhs, Exp rhs)
{ return new BinaryOp("<>", lhs, rhs); }
public static Exp operator ==(Exp lhs, int rhs)
{ return new BinaryOp("=", lhs, new Const<int>(rhs)); }
public static Exp operator !=(Exp lhs, int rhs)
{ return new BinaryOp("<>", lhs, new Const<int>(rhs)); }
public static Exp operator ==(int lhs, Exp rhs)
{ return new BinaryOp("=", new Const<int>(lhs), rhs); }
public static Exp operator !=(int lhs, Exp rhs)
{ return new BinaryOp("<>", new Const<int>(lhs), rhs); }
public static Exp operator ==(Exp lhs, string rhs)
{ return new BinaryOp("=", lhs, new Str(rhs)); }
public static Exp operator !=(Exp lhs, string rhs)
{ return new BinaryOp("<>", lhs, new Str(rhs)); }
public static Exp operator ==(string lhs, Exp rhs)
{ return new BinaryOp("=", new Str(lhs), rhs); }
public static Exp operator !=(string lhs, Exp rhs)
{ return new BinaryOp("<>", new Str(lhs), rhs); }
public override bool Equals(object obj) { return false; }
public override int GetHashCode() { return 0; }
}
// 二項演算
public class BinaryOp : Exp {
private string mnemonic_;
private Exp lhs_;
private Exp rhs_;
public BinaryOp(string m, Exp lhs, Exp rhs)
{ mnemonic_ = m; lhs_ = lhs; rhs_ = rhs; }
public override string ToString()
{ return lhs_.ToString() + " " + mnemonic_ + " " + rhs_.ToString(); }
}
// 文字列定数
class Str : Exp {
private string value_;
public Str(string value) { value_ = value; }
public override string ToString() { return '\"' + value_ + '\"'; }
}
// 定数
class Const<T> : Exp {
private T value_;
public Const(T value) { value_ = value; }
public override string ToString() { return value_.ToString(); }
}
// DB-カラム
class Column : Exp {
private string name_;
public Column(string name) { name_ = name; }
public override string ToString() { return name_; }
}
// DB-テーブル
class Table {
private string name_;
public Table(string name) { name_ = name; }
public string name() { return name_; }
public Column this[string c] {
get { return new Column(name_+"."+c); }
}
};
}
/* おためしだよーん */
class Program {
public static void Main() {
DB.Table phone = new DB.Table("phonebook");
DB.Table address = new DB.Table("addressbook");
// 電話帳にある名前とアドレス帳にある名前が一致し、"えぴ"ではない または20才じゃない
DB.Exp exp = phone["name"] == address["name"]
& phone["name"] != "えぴ"
| address["age"] != 20;
Console.WriteLine(exp);
}
}
教訓:「やればできる!」