使用委托代替接口

Dar*_*der 5 c# delegates interface

我读到你可以使用接口和代理来达到同样的目的.比如,您可以使用委托而不是接口.

有人能提供一个例子吗?我在简言之书中看到了一个例子,但我没有记住并且想要离开.

是否可以提供一些示例代码?用例?

谢谢.

Gro*_*roo 8

如果您的界面只有一个方法,那么使用委托会更方便.

比较以下示例:

使用界面

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)

您可以看到委托版本稍微小一些.

使用匿名方法和`Func`委托

如果你把这个带内置.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)