0

我知道我可以通过这样的方法:

Class A:
public void foo(Action<Class, Class, Class> bar)
{
    Class a;
    Class b;
    Class c;
    bar(a, b, c);
}
Class B:
public main()
{
    foo(bar);
}
protected void bar(Class a, Class b, Class c);

但我希望它更有条件:

Class A:
public void foo(bar) {
    Class a;
    Class b;
    Class c;
    Class d;
    if(condition A)
        bar(a, b, c);
    else
        bar(a, b, c, d);
}
Class B:
public main()
{
    foo(bar);
}
protected void bar(Class a, Class b, Class c);
protected void bar(Class a, Class b, Class c, Class d);

我该怎么做呢?

4

2 回答 2

1

没有办法传递方法组(一组同名但具有不同签名的方法),除了按名称作为字符串,然后使用反射。任何Delegate//表示必须是单个方法ExpressionMethodInfo

所以:你不能。


建议:

interface IBar {
    void bar(Class a, Class b, Class c);
    void bar(Class a, Class b, Class c, Class d);
}
class YourType : IBar {
    void IBar.bar(Class a, Class b, Class c) {...}
    void IBar.bar(Class a, Class b, Class c, Class d) {...}
    ...
    public main()
    {
        foo(this);
    }
}
于 2013-01-30T11:01:38.877 回答
1

您可以以bar不同的方式命名这两个函数,拥有两个重载foo函数并将条件从foo移至main

    protected void bar1(int a, int b, int c)
    {
        Console.WriteLine("a={0}, b={1}, c={2}", a, b, c);
    }

    protected void bar2(int a, int b, int c, int d)
    {
        Console.WriteLine("a={0}, b={1}, c={2}, d={3}", a, b, c, d);
    }

    public void foo(Action<int, int, int> bar)
    {
        int a = 1;
        int b = 2;
        int c = 3;
        bar1(a, b, c);
    }

    public void foo(Action<int, int, int, int> bar)
    {
        int a = 1;
        int b = 2;
        int c = 3;
        int d = 4;
        bar2(a, b, c, d);
    }

    public void main()
    {
        if (condition)
            foo(bar1);
        else
            foo(bar2);
    }
于 2013-01-30T11:14:06.210 回答