C#getter setter在List中溢出字符串

时间:2016-05-31 12:34:00

标签: c#

如何使用C#get set属性将字符串属性EndorseImageLink与逗号分隔为LIST EndorseImage s 链接  但我的代码似乎是递归调用

public string EndorseImageLink { get; set; }
    public List<string> EndorseImagesLink
            {
                get { return this.EndorseImagesLink; }
                set
                {

                    foreach (var endorseImageUrl in this.EndorseImageLink.Split(','))
                    {
                        if (endorseImageUrl.IsNotNullOrEmpty())
                        {
                            this.EndorseImagesLink.Add(endorseImageUrl);
                        }
                    }
                }
            }

4 个答案:

答案 0 :(得分:1)

它会导致递归调用,因为在EndorseImagesLink的getter中,您返回相同的EndorseImagesLink属性,它会一次又一次地调用相同的getter。 这样的事情是正确的:

private List<string> endorseImagesLink;
public List<sting> EndorseImagesLink
{
    get { return this.endorseImagesLink; }
    set { this.endorseImagesLink = value; }
}

答案 1 :(得分:0)

您需要属性访问的私有变量

private List<string> _endorseImagesLink = new List<string> ();
public List<string> EndorseImagesLink
        {
            get { return _endorseImagesLink ; }
            set
            {
                _endorseImagesLink.Clear();
                foreach (var endorseImageUrl in this.EndorseImageLink.Split(','))
                {
                    if (endorseImageUrl.IsNotNullOrEmpty())
                    {
                        _endorseImagesLink .Add(endorseImageUrl);
                    }
                }
            }
        }

您尝试在自己的setter中设置属性会发生什么。然后开始递归循环。

答案 2 :(得分:0)

看起来你有点混乱。我根本不认为你想要使用EndorseImagesLink的setter - 这实际上是一个取决于string的计算属性。

有两种方法。您可以在每次设置string时设置此项:

private string _linksDelimited;

public string LinksDelimited
{
    get { return _linksDelimited; }
    set
    {
        _linksDelimited = value;
        Links = value.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
    }
}

public IEnumerable<string> Links { get; private set; } = Enumerable.Empty<string>();

或者您可以按需计算结果:

public string LinksDelimited { get; set; } = string.Empty;

public IEnumerable<string> Links
    => LinksDelimited.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);

请注意,在这两种情况下,我都使用了string.Split重载来删除空条目 - 您不需要手动执行此操作。

答案 3 :(得分:0)

也许我误解了,但你想要那样的东西吗?

    public string EndorseImageLink
    {
        set
        {
            EndorseImagesLink.Clear();
            foreach (var endorseImageUrl in value.Split(',').Where(endorseImageUrl => !string.IsNullOrEmpty(endorseImageUrl)))
            {
                EndorseImagesLink.Add(endorseImageUrl);
            }
        }
    }

    public List<string> EndorseImagesLink
    {
        get { return _endorseImagesLink ?? (_endorseImagesLink = new List<string>()); }
        private set { _endorseImagesLink = value; }
    }