如何将重载的方法组作为单个参数传递?

时间:2013-01-30 10:58:23

标签: c#

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

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);

我该怎么做?

2 个答案:

答案 0 :(得分:1)

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

所以:你不能。


建议:

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);
    }
}

答案 1 :(得分: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);
    }