Build a static delegate from non-static method

后端 未结 5 1149
无人共我
无人共我 2021-01-06 08:28

I need to create a delegate to a non-static method of a class. The complications is that at the time of creation I don\'t have an intance to the class, only its class defini

5条回答
  •  被撕碎了的回忆
    2021-01-06 08:52

    You have two options, you can treat it like you would an extension method. Create an delegate to take in the object and any optional arguments and pass those arguments to the actual function call. Or create one using Delegate.CreateInstance as Dan mentioned.

    e.g.,

    string s = "foobar";
    
    // "extension method" approach
    Func substring1 = (s, startIndex) => s.Substring(startIndex);
    substring1(s, 1); // "oobar"
    
    // using Delegate.CreateDelegate
    var stype = typeof(string);
    var mi = stype.GetMethod("Substring", new[] { typeof(int) });
    var substring2 = (Func)Delegate.CreateDelegate(typeof(Func), mi);
    substring2(s, 2); // "obar"
    
    // it isn't even necessary to obtain the MethodInfo, the overload will determine
    // the appropriate method from the delegate type and name (as done in example 2).
    var substring3 = (Func)Delegate.CreateDelegate(typeof(Func), s, "Substring");
    substring3(3); // "bar"
    
    // for a static method
    var compare = (Func)Delegate.CreateDelegate(typeof(Func), typeof(string), "Compare");
    compare(s, "zoobar"); // -1
    

提交回复
热议问题