我有3个类(Rawmaterial、RawmaterialRepository和Storage),我想知道如何才能使Storage类具有为RawmaterialRepository创建的相同列表作为属性?在类程序中,我实例化了木头和存储库对象,并使用addRawmaterial方法将木头添加到存储库。最后,我实例化了storage1并调用了StockAlert方法,但它对我不起作用。出现一条错误消息,指出Warehouse类中的列表为空。这是我的代码。
public class Rawmaterial
{
public string name;
public int stock;
public Rawmaterial(string name, int stock)
{
this.name = name;
this.stock = stock;
}
}
public class RawmaterialRepository
{
public List<Rawmaterial> listRM = new List<Rawmaterial>();
public RawmaterialRepository()
{
listRM = new List<Rawmaterial>();
}
public void addRawmaterial(Rawmaterial rawmaterial)
{
listRM.Add(rawmaterial);
}
}
public class Storage
{
public string name;
public RawmaterialRepository listRM;
public Storage(string name)
{
this.name = name;
listRM = ; //this is a problem
}
public void StockAlert()
{
foreach (Rawmaterial rawmaterial in listRM.listRM) //this is a problem
{
if (rawmaterial.stock <= 10)
{
Console.WriteLine("Sotck Alert");
}
}
}
}
class Program
{
static void Main(string[] args)
{
Rawmaterial wood = new Rawmaterial("wood", 300) ;
RawmaterialRepository repository = new RawmaterialRepository();
repository.addRawmaterial(wood);
Storage storage1 = new Storage("storage1");
storage1.StockAlert();
}另外,你能帮我一下吗?我是个新手。
发布于 2021-04-30 20:32:03
您可以在存储构造函数中将存储库传递给存储:
public Storage(string name, RawmaterialRepository listRM)
{
this.name = name;
this.listRM = listRM; //this is a problem
}然后在Main中
Storage storage1 = new Storage("storage1", repository );发布于 2021-04-30 20:43:04
您希望使用名为“通过引用传递”的资源...尽管可以使用ref关键字明确表示,但C#的默认行为是按引用传递自定义类的对象
当您通过引用传递时,将传递对象引用(即存储对象的内存位置),以便在函数或其他类中不创建新对象,而只使用来自外部世界的对象。
仅供参考,在python中,默认行为也是按引用传递的。
public class Storage
{
public string name;
public RawmaterialRepository listRM;
public Storage(string name, ref RawmaterialRepository repository )
{
this.name = name;
listRM = repository; //this will be a reference to the same memory you created outside
}
public void StockAlert()
{
foreach (Rawmaterial rawmaterial in listRM.listRM) //this is a problem
{
if (rawmaterial.stock <= 10)
{
Console.WriteLine("Sotck Alert");
}
}
}
}
class Program
{
static void Main(string[] args)
{
Rawmaterial wood = new Rawmaterial("wood", 300) ;
RawmaterialRepository repository = new RawmaterialRepository();
repository.addRawmaterial(wood);
Storage storage1 = new Storage("storage1", repository); // just pass the object normally
storage1.StockAlert();
}https://stackoverflow.com/questions/67333924
复制相似问题