将类A中的方法添加到类B的委托中,并在c#中从类A调用该委托

本文关键字:调用 并在 方法 添加 将类 | 更新日期: 2023-09-27 18:04:14

如果事先不知道要添加哪个方法和a是什么类,如何将a类的方法添加到B类的委托中?然后从类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();
    }
}

我应该使用委托以外的东西吗?顺便说一下,我是用c#做的!

将类A中的方法添加到类B的委托中,并在c#中从类A调用该委托

mainClassMethod设置为静态,并通过类名MainClass访问它。此外,您不能将嵌套函数声明为类成员,您需要单独声明mainClassMethod

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);
    }

}

您还声明了委托void myDelegate(Class obj);,因此您需要将Class的实例作为参数传递。在我的例子中,我传递了由this引用找到的对象,这是一个您在。

中调用someMethod的对象。

现在你可以写:

class Class {
    public string someProperty;
    public delegate void myDelegate(Class obj);
    myDelegate handler = new myDelegate(MainClass.mainClassMethod); //no error
    public void someMethod() 
    {
        handler(this);
    }
}