【问题标题】:I've got two functions that differ only by some condition. Can it be unified?我有两个仅在某些条件下有所不同的功能。可以统一吗?
【发布时间】:2017-05-04 06:17:48
【问题描述】:

所以我有这两种方法:

    public static string Figure2D()
    {
        dynamic shapeValue;
        do
        {
            shapeValue = Presentation.Present();
        }
        while (shapeValue.Is3D);
        return shapeValue.ToString("R");
    }

    public static string Figure3D()
    {
        dynamic shapeValue;
        do
        {
            shapeValue = Presentation.Present();
        }
        while (!shapeValue.Is3D);
        return shapeValue.ToString("R");
    }

它们之间的唯一区别是 while 条件。如何将这两个合并为一个函数?传递参数值可能是必要且可接受的,但我喜欢保持简短。有什么想法吗?

【问题讨论】:

  • @stuartd 里面有一个!
  • @stuartd 一个被否定,另一个不是。
  • 小文又赢了,不好意思

标签: c# dry


【解决方案1】:

怎么样

public static string Figure(Predicate<dynamic> p)
    {
        dynamic shapeValue;
        do
        {
            shapeValue = Presentation.Present();
        }
        while (p(shapeValue));
        return shapeValue.ToString("R");
    }

【讨论】:

  • 我建议Func&lt;dynamic, bool&gt; 而不是Predicate 所以它可以简单地用作Figure(thing =&gt; !thing.Is3D)
  • 嗯,什么是谓词,我将如何通过条件? (抱歉,对 C# 有点陌生)
  • @Jesper:它是一个返回布尔值的委托(与返回您指定的任何内容的 Func 不同)。本质上,谓词 === Func<... bool>.. 有关详细信息,请查看 MSDN 或 VS 中的智能感知。
  • @quetzalcoatl 遗憾的是动态不能在 lambda 中使用
  • @quetzalcoatl 但是在这里使用Func&lt;dynamic,bool&gt;Predicate&lt;dynamic&gt; 有什么优势? Predicate 也可以简单地使用Figure(p =&gt; p.Is3D) 调用
猜你喜欢
  • 2019-11-15
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多