c# - Can I use some other class's function as a delegate? -
say have 2 classes, class , class b. class creates instance of class b. class has function pass method class b.
class { void main(string[] args) { b classb=new b(); delegatecaller(new delfunction(classb.thefunction()); // <-- won't compile (method name expected) delegatecaller(new delfunction(b.thefunction()); // <-- won't compile (object reference req'd) } public delegate string delfunction(); public delegatecaller(delfunction func) { system.console.writeline(func()); } } class b { public string thefunction() { return "i'm printing!!!"; } }
i'm not sure if syntax issue or it's can't do. maybe need define delegate in b, reference in a? b's this pointer?
it's syntax issue; rid of parentheses after classb.thefunction
- indicate wish invoke method.
delegatecaller(new delfunction(classb.thefunction));
do note there implicit conversion available method-group, can do:
delegatecaller(classb.thefunction);
also note creating own delegate-type in case unnecessary; use in-built func<string>
type.
edit: darin dimitrov points out, there unrelated issue of calling instance method though static method.
Comments
Post a Comment