![](/img/trans.png)
[英]C# .NET WinForms How do I copy instance of class from one List<class> to another List<class> using Clipboard
[英]How do I pass an object from one class into a list of another class?
我正在尝试将名为“itemRock”的 Item 类对象传递到名为“plyItems”的类 Inventory 列表中。
public class Item
{
public Item()
{
Item itemRock = new Item();
itemRock.Name = "Rock";
itemRock.Description = "It's a rock.";
}
}
public class Inventory
{
public Inventory()
{
List<string> plyItems = new List<string>();
plyItems.Add(itemRock.Name);
}
}
你在这里有几个问题。 首先,您的代码应如下所示:
public class Item
{
string Name = "Rock";
string Description = "It's a rock.";
}
public class Inventory
{
List<string> plyItems = new List<string>();
}
这样你的类中有私有变量。 您的类构造函数中的局部变量将在构造函数运行完毕后不复存在。
现在,如果您想将Item.Name
添加到plyItems
您有几个选择。
选项 1:您可以公开所有内容:
public class Item
{
public string Name = "Rock";
public string Description = "It's a rock.";
}
public class Inventory
{
public List<string> plyItems = new List<string>();
}
然后在代码中的某处创建Item
实例和Inventory
实例之后:
Item item = new Item();
Inventory inventory = new Inventory();
您可以将其添加到列表中:
inventory.plyItems.Add(item.Name);
选项 2:创建几个函数:
public class Item
{
string Name = "Rock";
string Description = "It's a rock.";
public string GetName()
{
return name;
}
}
public class Inventory
{
List<string> plyItems = new List<string>();
public void AddName(string _name)
{
plyItems.Add(_name);
}
}
然后使用与选项 1 相同的实例,调用:
inventory.AddName(item.GetName());
根据我的经验,这通常是更例外的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.