网上到处充斥这c#与java对比的文章,看了看,还是觉的MSDN上的一篇文章很全面和客观。《针对JAVA开发人员的C#编程语言》。
我的第一天C#学习,总体感觉C#在语言层面上保留了更多C++/C的特点,比如virtual,override关键字的使用,比如结构(值类型,存储在栈上),比如delegate(类似函数指针)。比较感兴趣的也就是delegate、事件和attribute方面。C#某种意义上讲比java稍微复杂,比C++简单。
参照语言规范写的例子,抽象类、继承的例子,可以扩展成一个简单计算器:
using System;
using System.Collections;
namespace VirtualDemo
{
public abstract class Expression
{
public abstract double Evaluate(Hashtable vars);
}
public class Constant : Expression
{
double value;
public Constant(double value)
{
this.value = value;
}
public override double Evaluate(Hashtable vars)
{
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("Unknown variable: " + name);
}
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("Unknown operator");
}
}
public class Test
{
public static void Main(string []args)
{
Expression e = new Operation(
new VariableReference("x"),
'*',
new Operation(
new VariableReference("y"),
'+',
new Constant(2)
)
);
Hashtable vars = new Hashtable();
vars["x"] = 3;
vars["y"] = 5;
Console.WriteLine(e.Evaluate(vars)); // Outputs "21"
vars["x"] = 1.5;
vars["y"] = 9;
Console.WriteLine(e.Evaluate(vars)); // Outputs "16.5"
}
}
}
再来一个委托的例子,函数作为变量的传递和使用,对有C++经验或者动态语言经验的人来说不会奇怪:
using System;
namespace DelegateDemo
{
delegate double Function(double x);
class Multiplier
{
double factor;
public Multiplier(double factor)
{
this.factor = factor;
}
public double Multiply(double x)
{
return x * factor;
}
}
class Test
{
static double Square(double x)
{
return x * x;
}
static double[] Apply(double[] a, Function f)
{
double[] result = new double[a.Length];
//直接通过f()调用
for (int i = 0; i < a.Length; i++) result[i] = f(a[i]);
return result;
}
static void Main()
{
double[] a = { 0.0, 0.5, 1.0 };
//delegate Function分别赋予了不同的方法
double[] squares = Apply(a, new Function(Square));
double[] sines = Apply(a, new Function(Math.Sin));
Multiplier m = new Multiplier(2.0);
double[] doubles = Apply(a, new Function(m.Multiply));
foreach (double b in doubles)
{
Console.WriteLine(b);
}
}
}
}
文章转自庄周梦蝶 ,原文发布时间5.17