Error: Cannot implicitly convert type 'void' to 'System.Collections.Generic.List'

后端 未结 7 1162
后悔当初
后悔当初 2021-01-07 21:59

I am trying to set a property of my .ascx controls from an .aspx using that control.

So in one of my .aspx which has this control in it, I have the

相关标签:
7条回答
  • new List<Item>().Add(item);
    

    This line returns void.

    Try:

    var list = new List<Item>();
    list.Add(item);
    ItemListt.ItemList = list;
    
    0 讨论(0)
  • 2021-01-07 22:20

    You can't do that because the Add function returns void, not a reference to the list. You can do this:

    mycontrol.ItemList = new List<Item>();
    mycontrol.ItemList.Add(item);
    

    or use a collection initializer:

    mycontrol.ItemList = new List<Item> { item };
    
    0 讨论(0)
  • 2021-01-07 22:26

    So long as ItemList is instantiated on your usercontrol, you can just do UserControl.ItemList.Add(item)

    0 讨论(0)
  • 2021-01-07 22:30

    The Add method doesn't return a reference to the list. You have to do this in two steps:

    ItemListt.ItemList = new List<Item>();
    ItemListt.ItemList.Add(item);
    

    Alternatively use a local variable to hold the reference before you put it in the property:

    List<Item> list = new List<Item>();
    list.Add(item);
    ItemListt.ItemList = list;
    
    0 讨论(0)
  • 2021-01-07 22:32
    ItemListt.ItemList = new List<Item>().Add(item);
    

    Does Add method return an instance of a list based class?

    EDIT: No, see this link for documentation on List<T>.Add

    EDIT2: Try writing this piece of code & see what is the return value of Add method.

    List<Item> items = new List<Item>();
    var modifiedList = items.Add(myItem);
    

    You will see that, the code should fail at Add because it returns void.

    0 讨论(0)
  • 2021-01-07 22:37

    After creating the List<Item> you're immediately calling Add on it, which is a method returning void. This cannot be converted to the type of ItemList.ItemList.

    You should do this instead:

    var list = new List<Item>();
    list.Add(item);
    ItemList.ItemList = list;
    
    0 讨论(0)
提交回复
热议问题