简体   繁体   中英

adding methods from class A to a delegate of class B and calling that delegate from class A in C#

How can I add a method from class A to a delegate of class B without knowing in advance which method I will be adding and what class A is? And then call that delegate from class A?

class Class {
    public string someProperty;

    public delegate void myDelegate(Class obj);

    myDelegate handler = new myDelegate(mainClassMethod); //here is the problem..

    public void someMethod() {
        handler();
    }
}

class MainClass {
    public static void Main() {
        Class classObj = new Class();

        classObj.someProperty = "hello";

        public void mainClassMethod(Class obj) {
            System.Console.WriteLine(obj.someProperty);
        }

        classObj.someMethod();
    }
}

Should I use something other than delegates for this? By the way I am doing this in C#!

make mainClassMethod static and access it via class name MainClass . Also you cant declare nested functions as class members, you need to declare mainClassMethod separately.

class MainClass {
    public static void Main()
    {
        Class classObj = new Class();

        classObj.someProperty = "hello";

        classObj.someMethod();
    }

    public static void mainClassMethod(Class obj) 
    {
        System.Console.WriteLine(obj.someProperty);
    }

}

Also you declared delegate void myDelegate(Class obj); so you need to pass instance of a Class as a parameter. In my example I pass object found by this reference, which is an object that you call someMethod at.

Now you can write:

class Class {

    public string someProperty;

    public delegate void myDelegate(Class obj);

    myDelegate handler = new myDelegate(MainClass.mainClassMethod); //no error

    public void someMethod() 
    {
        handler(this);
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM