函数指针没有指定参数和返回类型

时间:2018-03-13 11:57:43

标签: c# asp.net-mvc

我需要将方法的名称作为字符串传递。为了实现这一点,我创建了以下类:

public static class ActionExtension
{
    public static string GetName(this Func<int, Object> funcPtr)
    {
        return funcPtr.Method.Name;
    }

    .......
}

使用我这样做:

Func<int, Object> mailClickActionName = EmailView;    // sinature is => public ActionResult EmailView(int id)
Func<int, int, Object> apiFunc = new MailsController().Trashes;    // sinature is => public SomeClass Trashes()

string ItemAnchorAddress = mailClickActionName.GetName();

问题是我有很多方法(具体的操作)具有不同数量的参数,并且可能不返回任何值。在 ActionExtension 类中,我有许多复制的方法,它们的实现是相同的,但它们的签名是不同的。完整的ActionExtension类在这里:

public static class ActionExtension
{
    // Num #1
    public static string GetName(this Func<int, Object> funcPtr)
    {
        return funcPtr.Method.Name;
    }
    public static string GetName(this Func<Object> funcPtr)
    {
        // Exactly the same as #1
    }    
    public static string GetName(this Action<Object> funcPtr)
    {
        // Exactly the same as #1
    }
    public static string GetName(this Func<Object, Object, Object> funcPtr)
    {
        // Exactly the same as #1
    }

    // #2
    public static string GetNameWithController(this Func<int, Object> funcPtr)
    {
        string controller = funcPtr.Target.GetType().Name;
        return controller.Substring(0, controller.LastIndexOf("Controller")) + "/" + funcPtr.Method.Name + "/";
    }
    public static string GetNameWithController(this Func<int, int, Object> funcPtr)
    {
        // Exactly the same as #2
    }

    public static string GetNameWithController(this Func<Object> funcPtr)
    {
        // Exactly the same as #2
    }
    public static string GetNameWithController(this Func<Object, Object> funcPtr)
    {
        // Exactly the same as #2
    }
    public static string GetNameWithController(this Action<Object> funcPtr)
    {
        // Exactly the same as #2
    }

    public static string GetNameWithController(this Func<Object, Object, Object> funcPtr)
    {
        // Exactly the same as #2            
    }
}

我如何将所有方法总结为#1和#2?感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用Delegate类,它是所有代表的“父级”:

public static class Extensions {
    public static string GetName(this Delegate funcPtr) {
        return funcPtr.Method.Name;
    }
}

然后你可以将它用于所有代表:

static void Main() {
    Action test = Test;
    var name = test.GetName();
    name = ((Action<int>)Test2).GetName();            
}

public static void Test() {}
public static void Test2(int arg) { }