C#中属性set方法调用函数抛出System.StackOverflowException问题
异常原因分析
你遇到的System.StackOverflowException完全是因为Country类中Flag属性的实现错误:
- get访问器无限递归:
get { return Flag; }中,返回Flag会再次触发get访问器,形成无限循环; - set访问器无限递归:
set { Flag = IsoCountryCodeToFlagEmoji(value); }中,给Flag赋值会再次触发set访问器,同样陷入无限递归。
这种递归会不断消耗栈内存,最终导致栈溢出。
解决方案
根据你的需求(用两位国家代码生成国旗emoji),有两种更合理的实现方式:
方式一:使用私有后备字段修复属性递归问题
如果需要保留从外部赋值Flag的能力,给Flag属性添加私有存储字段,避免递归:
internal class Country { private string _flag; public string Name { get; set; } public string Flag { get { return _flag; } set { _flag = IsoCountryCodeToFlagEmoji(value); } } public string Code { get; set; } public string Dialcode { get; set; } public string IsoCountryCodeToFlagEmoji(string countryCode) { if (string.IsNullOrWhiteSpace(countryCode) || countryCode.Length != 2) return string.Empty; // 处理无效代码的边界情况 return string.Concat(countryCode.ToUpper().Select(x => char.ConvertFromUtf32(x + 0x1F1A5))); } }
方式二:将Flag改为基于Code的计算属性(更符合需求)
你的核心需求是用Code生成国旗emoji,因此可以把Flag设计为只读的计算属性,直接根据Code生成,同时忽略JSON中的flag字段:
using Newtonsoft.Json; internal class Country { public string Name { get; set; } // 标记为忽略JSON反序列化,因为我们要自己生成 [JsonIgnore] public string Flag => IsoCountryCodeToFlagEmoji(Code); public string Code { get; set; } public string Dialcode { get; set; } private string IsoCountryCodeToFlagEmoji(string countryCode) { if (string.IsNullOrWhiteSpace(countryCode) || countryCode.Length != 2) return string.Empty; return string.Concat(countryCode.ToUpper().Select(x => char.ConvertFromUtf32(x + 0x1F1A5))); } }
同时,优化Countries类中的文件读取逻辑,使用using语句确保资源正确释放:
internal class Countries { public List<Country> CountriesInfo { get; set; } public Countries() { using (StreamReader r = new StreamReader("C:\\Users\\folder\\Desktop\\Bol\\Bol\\Resources\\Data\\Countries.json")) { string jsonString = r.ReadToEnd(); CountriesInfo = JsonConvert.DeserializeObject<List<Country>>(jsonString); } } }
内容的提问来源于stack exchange,提问作者Sumchans
相关产品推荐
相关产品推荐

