请帮助我解决此委托问题,有一个 [英] Please help me to solve this delegate problem, there is an

查看:92
本文介绍了请帮助我解决此委托问题,有一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

评论中有错误,我不知道是什么原因,
它放红色,

there is an error in the comments, and i dont know what is the reason,
it puts red,,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication2
{
    //1 - first of all you have to define the delegate
    public delegate int Calculate (int value1 , int value2);
  public class MyClass
    {
        //2- create the method that will be assigned to the delegate object
        public  int Add(int value1, int value2) {
            return value1 + value2;
        }
       

        
        


    }
}









using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication2
{
    public class Driver
    {
        //3. Create the delegat object and assigning methods to those delegate objects
        MyClass mc = new MyClass();
        Calculate add = new Calculate(mc.Add);//////problem here  ?? why ?? please help

    }
}

推荐答案

显然,您并不真正了解自己在做什么以及为什么.只是在玩委托和委托实例?好的.您的问题是,您正在使用不需要的类的实例以及未定义的Calculate构造函数(这可能没有道理,也无法定义).您根本不需要此行.

也许这个正确的代码片段将帮助您获得一些想法:
Apparently, you don''t really understand what are you doing and why. Just playing with delegates and delegate instances? Good. You problem is that you are using instances of classes which you don''t need and the constructor of Calculate which you did not define (and which would not probably make sense, and you could not define). You never need this line at all.

Maybe this correct code fragment will help you to get some ideas:
internal delegate int Calculate(int left, int write);

internal static class MyClass {
    public static int Add(int left, int right) {
        return left + right;
    }
}

internal static class Calculator {
    internal static int ApplyBinaryOperator(int left, int right, Calculate operatorMethod) {
        return operatorMethod(left, right);
    }
}

class Program {
    static void Main(string[] args) {
        //for example
        int someValue = Calculator.ApplyBinaryOperator(2, 13, MyClass.Add);
        
        //you could have:
        Calculate delegateInstance = new Calculate(MyClass.Add); //could not do with class instance
        someValue = Calculator.ApplyBinaryOperator(12, 3, delegateInstance); //by why? See above
    }
}



祝你好运,

—SA



Good luck,

—SA


这篇关于请帮助我解决此委托问题,有一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆