当前位置:首页 > c#定义
return value; } }
public class variablereference: expression {
string name;
public variablereference(string name) {
this.name = name; }
public override double evaluate(hashtable vars) {
object value = vars[name];
if (value == null) {
throw new exception(\ }
return convert.todouble(value); } }
public class operation: expression {
expression left;
char op;
expression right;
public operation(expression left, char op, expression right) {
this.left = left;
this.op = op;
this.right = right; }
public override double evaluate(hashtable vars) {
double x = left.evaluate(vars);
double y = right.evaluate(vars);
switch(op) {
case + : return x + y;
case - : return x - y;
case * : return x * y;
case / : return x / y; }
throw new exception(\ } }
前面的4个类用于模型化算术表达式。例如,使用这些类的实例,表达式x+3能够被表示为如下的形式:
expression e = new operation(
new variablereference(\ +,
new constant(3));
expression实例的evaluate方法将被调用,以计算表达式的值,从而产生一个double值。该方法取得一个包含变量名(输入的键)和值(输入的值)的hashtable作为其自变量。evaluate方法是虚拟的抽象方法,意味着派生类必须重写它并提供实际的实现。
evaluate方法的constant的实现只是返回保存的常数。variablereference的实现在
hashtable中查找变量名,并且返回相应的值。operation的实现则首先计算左操作数和右操作数的值(通过递归调用evaluate方法),然后执行给定的算术运算。
下面的程序使用expression类,对于不同的x和y的值,计算表达式x*(y+2)。
using system;
using system.collections;
class test {
static void main() {
expression e = new operation(
new variablereference(\ *,
new operation(
new variablereference(\ +,
new constant(2)
) );
hashtable vars = new hashtable();
vars[\
vars[\
console.writeline(e.evaluate(vars)); //输出 \
vars[\
vars[\
console.writeline(e.evaluate(vars)); //输出 \ } }
1.6.5.5 方法重载
方法重载(method overloading)允许在同一个类中采用同一个名称声明多个方法,条件是它们的签名是惟一的。当编译一个重载方法的调用时,编译器采用重载决策(overload resolution)确定应调用的方法。重载决策找到最佳匹配自变量的方法,或者在没有找到最佳匹配的方法时报告错误信息。下面的示例展示了重载决策工作机制。在main方法中每一个调用的注释说明了实际被调用的方法。
class test {
static void f() {
console.writeline(\ }
static void f(object x) {
共分享92篇相关文档