gpt4 book ai didi

c# - 返回列表中对象的正确方法

转载 作者:太空宇宙 更新时间:2023-11-03 22:31:00 25 4
gpt4 key购买 nike

当我尝试返回填充对象的卡丁车列表时,我得到“systems.collections.generic.list”如何以正确的方式返回卡丁车?

方法

    public class AddToKart
{
public static List<KartItem> PutItemInKart(string input, int inputNumber, double inputPrice)
{
List<KartItem> kart = new List<KartItem>();
kart.Add(new KartItem() {
Item = input,
Pound = inputNumber,
Cost = inputPrice
});;
return kart;
}
}

对象检索数据

 public class KartItem
{
public string Item { get; set; }
public int Pound { get; set; }
public double Cost { get; set; }

public KartItem(string item, int pound, double cost)
{
Item = item;
Pound = pound;
Cost = cost;
}
public KartItem()
{
}
}

测试方法 PutItemInKart 测试项目磅数和成本来自对象。

  [Fact]
public void AddToKartMethodItem()
{
//Arrange
string expected = "fdfdfsds";

//Act
List<KartItem> items = AddToKart.PutItemInKart(expected, 3, 4.5);
string actual = items[0].Item;

//Assert
Assert.Equal(expected, actual);
}
[Fact]
public void AddKartMethodPound()
{
int expected = 3;
List<KartItem> numbers = AddToKart.PutItemInKart("mingt", expected, 4.45);
int actual = numbers[0].Pound;
Assert.Equal(expected, actual);
}
[Fact]
public void AddToKartMethodCost()
{
double expected = 34.56;
List<KartItem> cost = AddToKart.PutItemInKart("fdsf", 5, expected);
double actual = cost[0].Cost;
Assert.Equal(expected, actual);
}

最佳答案

这取决于您使用的场景。从您的代码中我可以看出您必须有一个 KartContainer 类,它必须包含所有与卡丁车相关的操作。

    public class KartContainer
{
private List<KartItem> Items = new List<KartItem>();

public void AddItem(KartItem item)
{
Items.Add(KartItem);
}

public List<KartItem> GetItems()
{
return Items;
}
}

And you can use it as the following:

        KartContainer kart = new KartContainer();

KartItem item = new KartItem()
{
Item = "",
Pound = 1,
Cost = 1
}

kart.AddItem(item);
List<KartItem> Items = kart.GetItems();

UPDATE: After your post update I would like to draw your attention about constructor definition, you must assign constructor parameters to local variables not the opposite.

    public KartItem(string item, int pound, double cost)
{
Item = item;
Pound= pound;
Cost = cost;
}

关于c# - 返回列表中对象的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57825486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com