演示使用委托与不使用的情景

时间:2014-12-03 15:10:08

标签: c# delegates

我已经看到很多代码示例实例显示了使用委托的好处。但是,如果可以将基于委托的代码示例与模拟相同进程但没有委托的代码进行比较,则可以更清楚地使用委托的目的。这也将展示编写应该使用委托的代码的相应问题,但事实并非如此。

如果有人可以在这里粘贴这样的样品,那会很棒。

编辑:我不是在征求意见。我要求提供针对同一问题展示两种不同解决方案的具体示例。其中一个解决方案使用委托而另一个解决方案不使用委托。

1 个答案:

答案 0 :(得分:2)

好的,这是一个我认为可能适当使用delegate的例子。我们有两种方法可以做一些常见的事情,但是在共同的工作中有不同的方法来完成任务。 IntConverter<T> delegate允许它们以完成调用方法特有的任务的方式传递。

如果它对你的问题很重要(我不确定),这个例子演示了要求实际的delegate类型(而不是通用的Func<>类型),因为委托类型本身有一个通用参数

private delegate int IntConverter<T>(T value);

public void DoSomething<T>(T value)
{
    DoCoreStuff(value, v => ConvertToIntInOneWay(v));
}

public void DoSomethingElse<T>(T value)
{
    DoCoreStuff(value, v => ConvertToIntInAnotherWay(v));
}

private void DoCoreStuff<T>(T value, IntConverter<T> intConverter)
{
    // Do a bunch of common stuff
    var intValue = intConverter(value);
    // Do a bunch of other core stuff, probably with the intValue
}

如果没有像这样的代表,也可以解决同样的情况:

public void DoSomething<T>(T value)
{
    DoFirstLotOfCoreStuff(value);
    DoSecondLotOfCoreStuff(ConvertToIntInOneWay(v));
}

public void DoSomethingElse<T>(T value)
{
    DoFirstLotOfCoreStuff(value);
    DoSecondLotOfCoreStuff(ConvertToIntInAnotherWay(v));
}

private void DoFirstLotOfCoreStuff<T>(T value)
{
    // Do a bunch of other core stuff, probably with the intValue
}

private void DoSecondLotOfCoreStuff(int intValue)
{
    // Do a bunch of other core stuff, probably with the intValue
}

...但这是一个较弱的解决方案,因为DoSomethingDoSomethingElse中的duplication以及现在需要的Sequential-coupling - 类型调用两个辅助方法

为了好玩,这是解决同一问题的另一种方法:

public interface IIntConverter<T>
{
    int Convert(T value);
}

public void DoSomething<T>(T value)
{
    DoCoreStuff(value, new ConvertToIntInOneWayIntConverter());
}

public void DoSomethingElse<T>(T value)
{
    DoCoreStuff(value, new ConvertToIntInAnotherWayIntConverter());
}

private void DoCoreStuff<T>(T value, IIntConverter<T> intConverter)
{
    // Do a bunch of common stuff
    var intValue = intConverter.Convert(value);
    // Do a bunch of other core stuff, probably with the intValue
}

...这是一个较弱的解决方案,因为我们发明了一个接口和两个实现,当我们想要做was simple enough委托时。