开发者

Is it possible to use reflection to turn a string into a function in c#?

public delegate 开发者_Go百科void SimpleDelegate();

public void mycode()
{
string str = "myfunction"; 

/*somehow use reflection to turn str into myfunction so this will compile*/
SimpleDelegate simpleDelegate = new SimpleDelegate(str);

}

public void myfunction() { } 


Find the method info

http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx

Convert it to a delegate

http://msdn.microsoft.com/en-us/library/53cz7sc6.aspx

Edit - Here is a small Linqpad snippet where I've setup an extension method off String to create delegates. There is no error checking!

void Main()
{
    var simpleDelegate = "test".CreateDelegate<Func<string>>(new Test());
    simpleDelegate().Dump();
}

class Test
{
    public string test() { return "hi"; }
}

public static class ExtensionMethods
{
    public static T CreateDelegate<T>(this string methodName,object instance) where T : class
    {
        return Delegate.CreateDelegate(typeof(T), instance, methodName) as T;
    } 
}


Use reflection to get a method:

GetType().GetMethod(str).Invoke(this, new object[0])


This walks you through exactly how to do it: http://www.codeproject.com/KB/cs/C__Reflection_Tutorial.aspx


You can use Reflection.Emit to create code but this would not take a string. Another alternative is CodeDOM which can take string.

Soultion

You can use Compiler to build an assembly and load. Look here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜