如果您的界面只有一个方法,那么使用委托会更方便.
比较以下示例:
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));
}
Run Code Online (Sandbox Code Playgroud)
// 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));
}
Run Code Online (Sandbox Code Playgroud)
您可以看到委托版本稍微小一些.
如果你把这个带内置.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));
}
Run Code Online (Sandbox Code Playgroud)