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

C S*_*per 1 .net c#

我有以下类结构:

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;}
}
Run Code Online (Sandbox Code Playgroud)

当我想填补这个:

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 = ""
                }
            );
        }                            
    );
}
Run Code Online (Sandbox Code Playgroud)

当我尝试将数据添加到GrandParentList列表时,这给了我错误:

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

我需要改变我的班级结构吗?我应该对代码进行哪些编辑?

Jon*_*eet 7

所以这部分是问题所在:

GrandParentData=new List<GrandParentData().Add(
    new GrandParentData { GrandFatherName = "",GrandMotherName =""});
Run Code Online (Sandbox Code Playgroud)

这里有三个问题:

  • 你没有关闭类型参数
  • 尽管这是对象初始化器的一部分,但最后你有一个分号
  • 您正在调用Add返回的方法void- 因此编译时错误

作为对最后一部分的进一步解释,忽略了你在对象初始化器中的事实,你的代码等同于尝试编写类似的东西:

List<int> list = new List<int>().Add(1);
Run Code Online (Sandbox Code Playgroud)

这是无效的,因为new List<int>().Add(1)不会返回任何内容.要Add明确地使用它,您需要单独声明变量:

List<int> list = new List<int>();
list.Add(1);
Run Code Online (Sandbox Code Playgroud)

当然,这在对象初始值设定项中不起作用,因为您需要提供单个表达式来设置属性.

解决方案是使用集合初始化程序.在我们的简单案例中,将是:

List<int> list = new List<int> { 1 };
Run Code Online (Sandbox Code Playgroud)

在你更复杂的情况下,你会这样做:

GrandParentData = new List<GrandParentData>
{ 
    new GrandParentData { GrandFatherName = "", GrandMotherName = "" }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以将其更改GrandParentData为只读属性,但已将其初始化,如下所示:

public List<GrandParentData> GrandParentData { get; } =
    new  List<GrandParentData>();
Run Code Online (Sandbox Code Playgroud)

然后你可以写:

GrandParentData =
{ 
    new GrandParentData { GrandFatherName = "", GrandMotherName = "" }
}
Run Code Online (Sandbox Code Playgroud)

......并且新的GrandParentData将被添加到现有的集合中.


Gil*_*een 5

您不能创建一个新列表,然后Add以这种方式调用它(分配值)

特定错误的原因是它Add是一个 void 方法,因此当您尝试将结果分配给属性时,您会收到错误。

检查以下代码,看到第一行没问题,但第二行出现错误:

new List<string>().Add("text");
var list = new List<string>().Add("text");
Run Code Online (Sandbox Code Playgroud)

虽然第一行实际上有效并且没有给出错误,但现在它已经有意义了,因为您没有对该集合的引用,并且初始化列表将由 GC 收集