C#:返回给定对象的委托和方法名 [英] C#: Return a delegate given an object and a method name

查看:430
本文介绍了C#:返回给定对象的委托和方法名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假如我是给定一个对象,并保存的方法名称的字符串,我怎么可以返回一个委托给该方法(该方法的?)?

Suppose I'm given an object and a string that holds a method name, how can I return a delegate to that method (of that method?) ?

例如:

MyDelegate GetByName(ISomeObject obj, string methodName)
{
    ...
    return new MyDelegate(...);
}

ISomeObject someObject = ...;
MyDelegate myDelegate = GetByName(someObject, "ToString");

//myDelegate would be someObject.ToString



先谢谢了。

Thanks in advance.

一件事 - 我真的不希望使用switch语句,即使它会工作,但一吨的代码

One more thing -- I really don't want to use a switch statement even though it would work but be a ton of code.

推荐答案

您需要使用的 Type.GetMethod 得到正确的方法,和的 Delegate.CreateDelegate 转换的的MethodInfo 成代表。完整的例子:

You'll need to use Type.GetMethod to get the right method, and Delegate.CreateDelegate to convert the MethodInfo into a delegate. Full example:

using System;
using System.Reflection;

delegate string MyDelegate();

public class Dummy
{
    public override string ToString()
    {
        return "Hi there";
    }
}

public class Test
{
    static MyDelegate GetByName(object target, string methodName)
    {
        MethodInfo method = target.GetType()
            .GetMethod(methodName, 
                       BindingFlags.Public 
                       | BindingFlags.Instance 
                       | BindingFlags.FlattenHierarchy);

        // Insert appropriate check for method == null here

        return (MyDelegate) Delegate.CreateDelegate
            (typeof(MyDelegate), target, method);
    }

    static void Main()
    {
        Dummy dummy = new Dummy();
        MyDelegate del = GetByName(dummy, "ToString");

        Console.WriteLine(del());
    }
}



迈赫达德的评论是一个伟大的,虽然 - 如果异常这个过载抛出 Delegate.CreateDelegate 都还好,可以简化 GetByName方法显著:

Mehrdad's comment is a great one though - if the exceptions thrown by this overload of Delegate.CreateDelegate are okay, you can simplify GetByName significantly:

    static MyDelegate GetByName(object target, string methodName)
    {
        return (MyDelegate) Delegate.CreateDelegate
            (typeof(MyDelegate), target, methodName);
    }



我从来没有使用这个我自己,因为我通常做检查的其他位)

I've never used this myself, because I normally do other bits of checking after finding the MethodInfo explicitly - but where it's suitable, this is really handy :)

这篇关于C#:返回给定对象的委托和方法名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆