我不太确定我正在尝试做什么,所以我正在努力从谷歌找到任何线索。

我有两种逻辑相同的方法,唯一不同的是它们在对象上使用的属性。

class Foo
{
   public int A(Bar bar)
   {
      return bar.A * 2;
   }

   public int B(Bar bar)
   {
      return bar.B * 2;
   }

   public int C(Bar bar)
   {
      return bar.C * 2;
   }
}

class Bar
{
   public int A;
   public int B;
   public int C;
}

我想要一个,而不是 Foo 中的三个单独的方法,签名看起来更像
public int X(Bar bar, ??? x)
{
   return bar.x * 2;
}

这可能吗?

最佳答案

internal class Program {
    private static void Main(string[] args) {
        var bar = new Bar {A = 1, B = 2, C = 3};
        Console.WriteLine(new Foo().X(bar, it => it.A));
        Console.WriteLine(new Foo().X(bar, it => it.B));

        // or introduce a "constant" somewhere
        Func<Bar, int> cFieldSelector = it => it.C;
        Console.WriteLine(new Foo().X(bar, cFieldSelector));
    }
}

internal class Foo {
    // Instead of using a field by name, give it a method to select field you want.
    public int X(Bar bar, Func<Bar, int> fieldSelector) {
        return fieldSelector(bar) * 2;
    }

    public int A(Bar bar) {
        return bar.A * 2;
    }

    public int B(Bar bar) {
        return bar.B * 2;
    }

    public int C(Bar bar) {
        return bar.C * 2;
    }
}

internal class Bar {
    public int A;
    public int B;
    public int C;
}

关于c# - 将 FieldName 作为参数传递,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/915795/

10-13 00:59