简体   繁体   English

如何使用列表C#返回对象

[英]How to return object using list c#

I have class Item.cs and I want return all items from my base with List<Item> ,.... 我有Item.cs类,我想用List<Item> ,....从我的基地返回所有项目。

so here is my code from WebService1.asmx 所以这是我来自WebService1.asmx的代码

[WebMethod]
public List<Item> GetMyItems()
{
    List<Item> listOfItems= new List<Item>();
    Item add = new Item();

    using (var db = new Baza()) // into in my database (this works fine)
    {  
        var lookUp = from a in db.listOfItems
                     select new
                     {
                         ID = a.ID,
                         Name = a.name,
                         Year= a.year,
                         Price= a.price
                     };

        foreach (var item in lookUp)
        {
            if (item.Name == "Usb")
            {
                add.name = item.Name;
                add.year = item.Year;
                add.price = item.Price;
                listOfItems.Add(add);
            }
        }
        return listOfItems;
    }
}

and I want now use this object in another .cs file. 我现在想在另一个.cs文件中使用此对象。 On example "Program.cs" 在示例“ Program.cs”上

So in program.cs I call method "GetMyItems": 因此,在program.cs中,我将方法称为“ GetMyItems”:

List<Item> myItems = myService.GetMyItems();

I had include my own library for my class "Item.cs" 我为类“ Item.cs”添加了自己的库

And on the end I get error: 最后我得到错误:

Error   1   Cannot implicitly convert type 'myItems.ServiceReference1.Item[]' to 'System.Collections.Generic.List<myLibrary.Item>'

My purpose is that I can in Program.cs use every property(in my case: name, year, price) for "listView" 我的目的是我可以在Program.cs中将每个属性(以我的情况为例:名称,年份,价格)用于“ listView”

For all the answers in advance thanks. 对于所有的答案提前谢谢。

When you use the method through the service it will automatically cast List<Item> to the basic data type Item[] . 通过服务使用该方法时,它将自动将List<Item>转换为基本数据类型Item[]

To work around this I see two options: 要变通解决此问题,我看到两个选择:

  1. Use the var keyword, and continue using the data type Item[] . 使用var关键字,然后继续使用数据类型Item[]

     var myItems = myService.GetMyItems(); 
  2. Cast it back to IEnumerable<Item> : 将其投射回IEnumerable<Item>

     var myItems = myService.GetMyItems().ToList(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM