网络核心:解决 "Add a way to break out of this property accessor's recursion"

Net Core: Resolve "Add a way to break out of this property accessor's recursion"

我正在尝试创建一个简单的 class。 ColumnSort 成员是逗号分隔文本“Car,Book,Food”中的项目列表。

ColumnSortList 创建一个列表

  1. 汽车
  2. 图书
  3. 食物

C# 和 SonarQube 提到了像错误这样的项目

Get: Add a way to break out of this property accessor's recursion.

Set: Use the 'value' parameter in this property set accessor declaration

我将如何解决这些问题以使警告/错误(在 SonarQube 中)消失?也愿意提高代码效率。

注意:columnSortList 纯粹应该是 ColumnSort 字符串中的只读计算字段。

public class PageModel
{
    public int Page { get; set; }
    public int Limit { get; set; }
    public string ColumnSort { get; set; }

    public IEnumerable<string> columnSortList
    {
        get
        {
            return columnSortList;
        }
        set
        {
            if (ColumnSort == null)
            {
                columnSortList = null;
            }
            else
            {
                columnSortList = ColumnSort.Split(',')
                             .Select(x => x.Trim())
                             .Where(x => !string.IsNullOrWhiteSpace(x))
                             .AsEnumerable();
            }
        }
    }

如果 columnSortList 是纯只读的,从 ColumnSort 计算而来,那么您根本不应该有 set 方法。所有逻辑都应该像这样放在 get 中:

public IEnumerable<string> columnSortList
{
    get
    {
        if (ColumnSort == null)
        {
            return Enumerable.Empty<string>();
        }
        else
        {
            return ColumnSort.Split(',')
                             .Select(x => x.Trim())
                             .Where(x => !string.IsNullOrWhiteSpace(x))
                             .AsEnumerable();
        }
    }
}

你的 getter 正在返回自己,你不能这样做,你的 setter 正在设置自己,你也不能这样做。这似乎是你想要的:

public IEnumerable<string> columnSortList
{
    get
    {
        if (ColumSort == null)
        {
            return new List<string>();
        }
        else
        {
            return ColumnSort.Split(',')
                         .Select(x => x.Trim())
                         .Where(x => !string.IsNullOrWhiteSpace(x))
                         .AsEnumerable();
        }
    }
}