gpt4 book ai didi

c# - 为什么字符串不实现 IList

转载 作者:太空狗 更新时间:2023-10-29 22:05:21 24 4
gpt4 key购买 nike

标题说明了一切

为什么 String实现 IEnumerable<char>而不是 IList<char>

字符串有长度,您已经可以从特定索引中获取元素。
并且可以表明它是不可变的 ICollection<char>.IsReadOnly .

那么它有什么问题呢?我错过了什么吗?

许多答案都指出了这一点:没有单独的只读列表/集合的界面,但是作为ReadOnlyCollection<T>显示我认为它绝对有可能并且它是IsReadOnly专为此类情况设计的属性。

   public class String : IList<char>
{
int IList<char>.IndexOf(char item)
{
// ...
}

void IList<char>.Insert(int index, char item)
{
throw new NotSupportedException();
}

void IList<char>.RemoveAt(int index)
{
throw new NotSupportedException();
}

char IList<char>.this[int index]
{
set
{
throw new NotSupportedException();
}
}

void ICollection<char>.Add(char item)
{
throw new NotSupportedException();
}

void ICollection<char>.Clear()
{
throw new NotSupportedException();
}

public bool Contains(char item)
{
// ...
}

public void CopyTo(char[] array, int arrayIndex)
{
// ...
}

int ICollection<char>.Count
{
get { return this.Length; }
}

public bool IsReadOnly
{
get { return true; }
}

bool ICollection<char>.Remove(char item)
{
throw new NotSupportedException();
}

// ...
}

最佳答案

主要是因为IList继承自 ICollection , 和字符串不支持可变行为 ICollection promises(添加、删除和清除)- 当您从字符串中添加或删除字符元素时,它会创建一个新字符串。


实现界面的部分是糟糕的设计。有时您可能出于必要而这样做,但这绝不是一个好的选择。最好拆分接口(interface)。 (.NET 集合接口(interface)可能应该被拆分,以将可变成员与诊断成员分开。)像 IsReadOnly 这样的元函数。使界面不连贯,更难使用。

因此,即使一个字符串在很多方面都是一个列表——你可以索引一个字符串并找到其中的字符数——很少有人真的想像这样对待一个字符串一个IList<char> ,特别是在后 3.5 世界中,当有简单的转换可用时,可以很容易地从 IEnumerable<char> 中获取此信息。 .

关于c# - 为什么字符串不实现 IList<char>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7135270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com