学C#有大半年了,这篇是我刚从Java转到C#时写的文章。这次转移博客,一起挪了过来,文章写的不好,希望大家看了不要拍砖哈。
刚从Java转到C#,对C#和dotnet平台了解还不深,这里只是发表一下个人从Java角度对C#的理解。
今天刚刚看到C#中的函数委托机制,觉得C#中这个机制非常好,给编程以很大的方便。Java中只有对象的引用,而C#中增加了对值类型(C#中的值类型包括 primitives,枚举和结构体)的引用和函数的引用。
个人觉得值类型的引用用处不大,不仅对提高C#程序的质量没有什么意义,而且会使没有经验的程序员滥用它。比如,一个函数的有一个ref参数或者out参数,那么函数对这个引用参数的值的修改都会影响到外部程序的变量的值,无形中增加了函数和外部程序的耦合性。
class Program
2

{
3
static void double(ref int i)
4
{
5
i *= 2;
6
}
7
8
static void main(string[] args)
9
{
10
int i = 3;
11
double(i);
12
}
13
}
而函数的引用(函数委托就是一种用引用表示函数的机制)则相当有用。试想想,函数的引用本质上是把一个代码块用一个引用变量来表示,你可以根据不同的情况,选择不同的代码块,然后执行它。这种特性在Java和c中是不曾提供的(Java中可以用模式实现),它可以大大减少我们代码量,运用这种特性也可以使我们面对变化的需求时修改的代码量更少。
1
Using directives#region Using directives
2
using System;
3
using System.Collections.Generic;
4
using System.Text;
5
#endregion
6
7
namespace Ch06Ex05
8

{
9
class Program
10
{
11
delegate double ProcessDelegate(double param1, double param2);
12
13
static double Multiply(double param1, double param2)
14
{
15
return param1 * param2;
16
}
17
18
static double Divide(double param1, double param2)
19
{
20
return param1 / param2;
21
}
22
23
static void Main(string[] args)
24
{
25
ProcessDelegate process;
26
Console.WriteLine("Enter 2 numbers separated with a comma:");
27
string input = Console.ReadLine();
28
int commaPos = input.IndexOf(',');
29
double param1 = Convert.ToDouble(input.Substring(0, commaPos));
30
double param2 = Convert.ToDouble(input.Substring(commaPos + 1,
31
input.Length - commaPos - 1));
32
Console.WriteLine("Enter M to multiply or D to divide:");
33
input = Console.ReadLine();
34
if (input == "M")
35
process = new ProcessDelegate(Multiply);
36
else
37
process = new ProcessDelegate(Divide);
38
Console.WriteLine("Result: {0}", process(param1, param2));
39
Console.ReadKey();
40
}
41
}
42
}
上面这个程序先要求用户输入两个数,然后根据用户的要求选择是进行乘法运算还是除法运算,最后算出结果。我们再来看看同样的功能用Java怎么实现。

Computer.java
1
package test;
2
3
public interface Computer
{
4
Double compute(Double x, Double y);
5
}
Multiply.Java
1
package test;
2
3
public class Multiply implements Computer
{
4
5
public Double compute(Double x, Double y)
{
6
Double re = x*y;
7
return re;
8
}
9
} Divide.java
1
package test;
2
3
public class Divide implements Computer
{
4
5
public Double compute(Double x, Double y)
{
6
Double re = x/y;
7
return re;
8
}
9
} Compute.java
posted @ 2008-07-06 22:02
Baozi 阅读(27)
评论(0) 编辑 收藏 网摘 所属分类:
开发技术