[笔记]接口VS代理
声明代理
public delegate void Transfrom(int i);
定义工具类
public class Util
{
public static void Square(int i) //此方法用于在控制台打印I*I
{
i = i * i;
Console.WriteLine(i);
}
public static void Print(int i) //此方法写入文件
{
i = i * i;
System.IO.File.WriteAllText("C:\\Test.txt", i.ToString());
}
public static void TransformALL(int value,Transfrom t)
{
t += Util.Print; //多播委托
t(value);
}
}
测试类
public class Test
{
public static void Main()
{
Util.TransformALL(2, Util.Square);
Console.Read();
}
}
---------------------------------------------------------------------------------------------------------------------------------------
以下是接口实现
public interface ITransformer
{
int Transform (int x);
}
public class Util
{
public static void TransformAll (int[] values, ITransformer t)
{
for (int i = 0; i < values.Length; i++)
values[i] = t.Transform(values[i]);
}
}
class Test : ITransformer
{
static void Main( )
{
int[] values = new int[] {1, 2, 3};
Util.TransformAll(values, new Test( ));
foreach (int i in values)
Console.WriteLine (i);
}
public int Transform (int x) { return x * x; }
}
接口的弊端
In the ITransformer example, we don't need to multicast. However, the interface defines only a single method. Furthermore, our listener may need to implement ITransformer multiple times, to support different transforms, such as square or cube. With interfaces, we're forced into writing a separate type per transform, since Test can only implement ITransformer once. This is quite cumbersome:

浙公网安备 33010602011771号