Microsoft.CSharp.RuntimeBinder异常:动态对象Name属性调用失败
问题原因
你遇到的RuntimeBinderException是因为匿名类型的访问级别是internal,如果调用代码和CreateRegion方法不在同一个程序集里,用dynamic接收返回值时,运行时绑定器无法访问internal类型的成员——即便调试时能看到这些字段,动态调用也会失败。
解决方案
方案1:替换匿名类型为具名公共类
定义公开类承载返回数据,跨程序集也能正常访问属性:
// 定义公共类 public class CountryInfo { public string Name { get; set; } public int Population { get; set; } public Region[] Regions { get; set; } public string President { get; set; } } // 修改CreateRegion方法 internal dynamic CreateRegion(dynamic req) { Regions = new Region[] { new("NY"), new("MI") }; return new CountryInfo { Name = Name, Population = Population, Regions = Regions, President = President }; }
方案2:将方法改为public(仅限同程序集调用场景)
如果调用代码和CreateRegion在同一个程序集里,把方法访问级别改成public即可:
public dynamic CreateRegion(dynamic req) { Regions = new Region[] { new("NY"), new("MI") }; return new { Name, Population, Regions, President }; }
方案3:使用ExpandoObject构建动态对象
ExpandoObject的成员默认公开可访问,不受程序集访问级别限制:
using System.Dynamic; internal dynamic CreateRegion(dynamic req) { Regions = new Region[] { new("NY"), new("MI") }; dynamic result = new ExpandoObject(); result.Name = Name; result.Population = Population; result.Regions = Regions; result.President = President; return result; }
内容的提问来源于stack exchange,提问作者hello B
相关产品推荐
相关产品推荐

