c# - 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);
}
}
解决方案
您遇到此错误是因为MyDelegate
它是一个实例方法(上面没有static
关键字)并且它正在static
上下文(Main
)上使用。要修复错误,您需要以MyDelegate
这种方式声明:
public static void MyDelegate (List<Product> e)
{
// do some stuff
}
推荐阅读
- c# - 执行插入事务时获取所有用户表的行数
- jquery - jQuery 在 wordpress 网站中不起作用
- mysql - 如何将 ROW_FORMAT=DYNAMIC 应用于现有表
- sql - 插入从一个表创建多个寄存器到另一个
- azure - 有没有办法从 Azure Cloud Shell 下载文件?
- jenkins - 库 Jenkins Step 无法动态加载方法
- javascript - ReactJS 与 Google Maps - 随时显示一个信息窗口
- ssl - 从 TLS WebSocket 连接中剥离 SNI 信息
- mysql - Nuxt.js 和 axios 不适用于 Express 服务器
- keras - 使用 LSTM 预测多个时间序列预测