首页 > 解决方案 > C# - 如何传递列表以委托为参数

问题描述

本质上,我要做的是创建一个委托,我想将函数传递给一个方法——该方法将获取一个产品对象列表并执行某些计算。

不幸的是,我收到一条错误消息

main.cs(11,40):错误 CS0120:访问非静态成员“MainClass.MyDelegate(System.Collections.Generic.List)”需要对象引用编译失败:1 个错误,0 个警告编译器退出状态 1

我的问题是为什么我很难将列表传递给代表 - 我做错了什么?

谢谢你和亲切的问候


using System;
using System.Collections.Generic;
using System.Collections;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine ("Hello World");
    MyCart MyBasket =  new MyCart();
    MyBasket.Initialize();
    //Console.WriteLine(MyBasket.basket.Count);
    MyBasket.BuyItem("Iphone", 300.3m, MyDelegate );
  }

  public void MyDelegate (List<Product> e){
    // this is where i am performing my delegate
    if (e.Count > 2)
    {
      Console.WriteLine($"This is delegate Talking our current Cart has more than 2 items inside, in fact the count is  {e.Count}");
    }
    else

    {
      Console.WriteLine($"This is delegate Talking our current Cart has less than 2 items inside, in fact the count is  {e.Count}");
    }
  }
}

public class MyCart
{
//public delegate void ObjectCheck(List<Product> basket) ;

public List<Product> basket = new List<Product>();
public delegate void ObjectCheck(List<Product> basket) ;
public void Initialize (){
  // this is our Cart Class constructor
  basket.Add(new Product { ItemName = "Book", ItemPrice = 4.9m });
  basket.Add(new Product { ItemName = "Milk", ItemPrice = 3.5m });
}

public void BuyItem (string i, decimal p, ObjectCheck mymethod)
{
  basket.Add(new Product {ItemName = i, ItemPrice = p});

  mymethod(basket);

}
}

标签: c#listgenericsparametersdelegates

解决方案


您遇到此错误是因为MyDelegate它是一个实例方法(上面没有static关键字)并且它正在static上下文(Main)上使用。要修复错误,您需要以MyDelegate这种方式声明:

public static void MyDelegate (List<Product> e)
{
    // do some stuff
}

推荐阅读