Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“对象”不包含“名称”的定义

问题描述 投票:0回答:1

尝试解开这个谜团! 我的动态结构仅在某些情况下有效: 这是我安装动态对象的地方

string President { get; set; } = "Boss";
string Name { get; set; } = "USA";
int Population { get; set; } = 600000;
Region[] Regions { get; set; }

internal dynamic CreateRegion(dynamic req)
{
    Regions = new Region[] { new("NY"), new("MI") };
    return new
    {
        Name = this.Name,
        Population = this.Population,
        Regions = Regions,
        Presindent = this.President,
    };

}

这就是我使用动态类型的地方:

var response = italy.CreateRegion(req);
Console.WriteLine(response);
Console.WriteLine(response.Name);
Console.WriteLine(response.Population);
Console.WriteLine(response.President);
foreach (var region in response.Regions)
{
    Console.WriteLine(region.Name.ToString());
}

字段名称存在于对象中,我可以看到这一点。但是当我尝试调用它时,它返回错误:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“对象”确实 不包含“名称”的定义

棘手的是,如果我删除

地区 = 地区

,来自

return new
{
    Name = this.Name,
    Population = this.Population,
    Regions = Regions,
    Presindent = this.President,
};
c# .net reflection
1个回答
0
投票

在这段代码中,您将“President”字段错误地拼写为“President”

return new
    {
        Name = this.Name,
        Population = this.Population,
        Regions = Regions,
        Presindent = this.President,
    };

我认为您与“Name”有同样的情况,也许您使用了另一个“a”字符或其他字符。重点是,它是拼写错误,所以尝试更改它。另外,如果你想进一步使用动态,你可以这样写:

 return new
        {
            Name,
            Population,
            Regions,
            President,
        };

但我建议使用类。根据功能,我假设您想要为国家/地区创建区域。您只需创建与 Country 类分开的 Region 即可做到这一点,例如如下所示:

class Region{
    public static Region Create(... fields) => new (){...fields}
}

只需将其直接添加到您的国家/地区实体即可:

var region = Region.Create(data);
italy.Regions.Add(region);
© www.soinside.com 2019 - 2024. All rights reserved.