简体   繁体   English

无法将类型void隐式转换为List

[英]Cannot implicitly convert type void to List

I have below class structure: 我有下面的类结构:

class Child
{
    public List<ParentData> ParentData { get; set; }
}

class ParentData
{
    public string FatherName {get;set;}
    public string MotherName {get;set;}
    public List<GrandParentData> GrandParentData{ get; set; }
}

class GrandParentData
{
    public string GrandFatherName {get;set;}
    public string GrandMotherName {get;set;}
}

When I am trying to fill this: 当我尝试填写此内容时:

foreach (var item in res)
{
    obj.StoryData.Add(
        new StoryData
        {
            FatherName = item.FatherName,
            MotherName = item.Description,                                                                        
            GrandParentData = new List<GrandParentData().Add(
                new GrandParentData 
                { 
                    GrandFatherName = "",
                    GrandMotherName = ""
                }
            );
        }                            
    );
}

This is giving me error when I am trying to add data to GrandParentList List: 当我尝试将数据添加到GrandParentList列表时,这给了我错误:

Cannot implicitly convert type void to List 无法将类型void隐式转换为List

Do I need to change my class structure? 我需要更改班级结构吗? What edits should I make to my code? 我应该对代码进行哪些编辑?

So this part is the problem: 所以这是问题所在:

GrandParentData=new List<GrandParentData().Add(
    new GrandParentData { GrandFatherName = "",GrandMotherName =""});

There are three problems here: 这里有三个问题:

  • You're not closing the type argument 您没有关闭类型参数
  • You've got a semi-colon at the end, despite this being part of an object initializer 尽管这是对象初始化程序的一部分,但最后还是以分号结尾
  • You're calling the Add method, which returns void - hence the compile-time error 您正在调用Add方法,该方法返回void因此出现编译时错误

As further explanation for the last part, ignoring the fact that you're in an object initializer, your code is equivalent to trying to write something like: 作为最后一部分的进一步说明,忽略您在对象初始化器中的事实,您的代码等效于尝试编写类似以下内容的代码:

List<int> list = new List<int>().Add(1);

That's invalid because new List<int>().Add(1) doesn't return anything. 这是无效的,因为new List<int>().Add(1)不返回任何内容。 To use Add like that explicitly, you'd need to declare the variable separately: 要显式使用Add ,您需要分别声明变量:

List<int> list = new List<int>();
list.Add(1);

That doesn't work within an object initializer of course, as you need to provide a single expression to set the property. 当然,这在对象初始化器中是行不通的,因为您需要提供一个表达式来设置属性。

The solution is to use a collection initializer instead. 解决方案是改用集合初始化器 In our simple case that would be: 在我们的简单情况下,将是:

List<int> list = new List<int> { 1 };

In your more complex case, you'd do this: 在更复杂的情况下,您可以这样做:

GrandParentData = new List<GrandParentData>
{ 
    new GrandParentData { GrandFatherName = "", GrandMotherName = "" }
}

Alternatively, you could change GrandParentData to be a read-only property, but have it already initialized, like this: 另外,您可以将GrandParentData更改为只读属性,但已将其初始化,如下所示:

public List<GrandParentData> GrandParentData { get; } =
    new  List<GrandParentData>();

Then you could just write: 然后,您可以编写:

GrandParentData =
{ 
    new GrandParentData { GrandFatherName = "", GrandMotherName = "" }
}

... and the new GrandParentData would be added to the existing collection. ...,新的GrandParentData将添加到现有集合中。

You cannot create a new list and then call Add on it in this manner (of assigning value) 您不能创建新列表,然后以这种方式(分配值)在其上调用Add

  • Instead of: 代替:

     GrandParentData = new List<GrandParentData>().Add(...) 
  • Write (using collection initializer syntax): 写(使用集合初始化器语法):

     GrandParentData = new List<GrandParentData> { new GrandParentData { ... } } 

Reason for specific error is that Add is a void method, and therefore when you try to assign the result to the property you get the error. 发生特定错误的原因是Add是一个无效方法,因此,当您尝试将结果分配给属性时,会出现错误。

Check the following code and see that first line is okay but second gives error: 检查以下代码,看看第一行还可以,但是第二行给出了错误:

new List<string>().Add("text");
var list = new List<string>().Add("text");

Though first line actually works and does not give an error it has now sense in it as you have no reference to that collection and the initialized list will be collected by the GC 尽管第一行实际上可以工作并且不会产生错误,但是由于您没有对该集合的引用,因此现在已经可以理解,并且初始化列表将由GC收集

You are trying to assign the result of the Add method (a void ) to the variable. 您试图将Add方法的结果( void )分配给变量。 That is not possible. 这是不可能的。 void can't be assigned to a variable. 不能将void分配给变量。

Here come collection initializers to the rescue: 收集初始值设定项以进行救援:

GrandParentData = new List<GrandParentData()
                  { new GrandParentData { GrandFatherName = "",GrandMotherName =""}
                  }

Source of Issue is this piece of code: 发出源是这段代码:

GrandParentData=new List<GrandParentData().Add(
new GrandParentData { GrandFatherName = "",GrandMotherName =""}

Why ? 为什么呢

GrandParentData is of type List<GrandParentData> and List<GrandParentData>.Add method returns void, so its simply saying you cannot map a List<GrandParentData> to void return and that's fair. GrandParentData的类型为List<GrandParentData>List<GrandParentData>.Add方法返回void,因此它只是说您不能将List<GrandParentData>映射为void return,这是公平的。 Following is the implementation of the List<T>.Add 以下是List<T>.Add的实现。

 public void Add(T item) {
            if (_size == _items.Length) EnsureCapacity(_size + 1);
            _items[_size++] = item;
            _version++;
        }

Check here 在这里检查

Solution would be: 解决方案是:

As listed in other answers above where you do object addition as part of the List creation, in fact you may simply do: 如以上其他答案中列出的那样,您在列表创建过程中进行对象添加,实际上,您可以简单地执行以下操作:

GrandParentData = new List<GrandParentData() { new GrandParentData()}

And assign the default values in the constructor as follows: 并在构造函数中分配默认值,如下所示:

class GrandParentData
{
    public string GrandFatherName {get;set;}
    public string GrandMotherName {get;set;}

    public GrandParentData()
    {
       GrandFatherName = "";
       GrandMotherName = "";

    }
}

On another note another surprising point related to model design, there's a model named GrandParentData and you have a public List<GrandParentData> GrandParentData{ get; set; } 另一方面,与模型设计有关的另一个令人惊讶的地方是,有一个名为GrandParentData的模型,您有一个public List<GrandParentData> GrandParentData{ get; set; } public List<GrandParentData> GrandParentData{ get; set; } public List<GrandParentData> GrandParentData{ get; set; } , this in general is confusing, ideally use a suffix to show that its a collection public List<GrandParentData> GrandParentData{ get; set; } ,这通常是令人困惑的,理想情况下使用后缀来表明它是一个集合

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

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