我读到可以使用接口和委托来达到相同的目的。例如,你可以使用委托代替接口。
有人可以提供一个例子吗?我在《Nutshell》书中看到过一个例子,但我忘记了,想问问。
能否提供一些示例代码?用例?
谢谢。
public interface IOperation
{
int GetResult(int a, int b);
}
public class Addition : IOperation
{
public int GetResult(int a, int b)
{
return a + b;
}
}
public static void Main()
{
IOperation op = new Addition();
Console.WriteLine(op.GetResult(1, 2));
}
// delegate signature.
// it's a bit simpler than the interface
// definition.
public delegate int Operation(int a, int b);
// note that this is only a method.
// it doesn't have to be static, btw.
public static int Addition(int a, int b)
{
return a + b;
}
public static void Main()
{
Operation op = Addition;
Console.WriteLine(op(1, 2));
}
您可以看到委托版本稍微小一些。
如果您将此与内置的.NET泛型委托(Func<T>
, Action<T>
等)和匿名方法结合使用,您可以用以下代码替换整个代码:
public static void Main()
{
// Func<int,int,int> is a delegate which accepts two
// int parameters and returns int as a result
Func<int, int, int> op = (a, b) => a + b;
Console.WriteLine(op(1, 2));
}
Func<int, Func<int, int>> op = a => b => a + b; Console.WriteLine(op(1)(2));
- phoog委托可以像单方法接口一样使用:
interface ICommand
{
void Execute();
}
delegate void Command();
当您使用委托:
public delegate T Sum<T>(T a, T b);
class Program
{
static void Main(string[] args)
{
int sum = Test.Sum(new[] {1, 2, 3}, (x, y) => x + y);
}
}
public static class Test
{
public static int Sum<T>(IEnumerable<T> sequence, Sum<T> summator)
{
// Do work
}
}
当你使用接口时:
public interface ISummator<T>
{
T Sum(T a, T b);
}
public class IntSummator : ISummator<int>
{
public int Sum(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
int sum = Test.Sum(new[] {1, 2, 3}, new IntSummator());
}
}
public static class Test
{
public static int Sum<T>(IEnumerable<T> sequence, ISummator<T> summator)
{
// Do work
}
}
public interface IArithmeticOperations<T>
{
T Sum(T a, T b);
T Sub(T a, T b);
T Div(T a, T b);
T Mult(T a, T b);
//
}
public class IntArithmetic : IArithmeticOperations<int>
{
public int Sum(int a, int b)
{
return a + b;
}
public int Sub(int a, int b)
{
return a - b;
}
public int Div(int a, int b)
{
return a / b;
}
public int Mult(int a, int b)
{
return a * b;
}
}
class Program
{
static void Main(string[] args)
{
int sum = Test.SumOfSquares(new[] {1, 2, 3}, new IntArithmetic());
}
}
public static class Test
{
public static int SumOfSquares<T>(IEnumerable<T> sequence, IArithmeticOperations<T> summator)
{
// Do work
}
}