为什么不允许从字符串中通过"ref"获取字符?



我很好奇,为什么这个有效。。。

static void Main(string[] args)
{
ReadOnlySpan<char> text = "Hello";
ref readonly char c = ref text[0];
}

但是这个是不允许的?

static void Main(string[] args)
{
string text = "Hello";
// Error CS8156 An expression cannot be used in this context because it may not be passed or returned by reference
ref readonly char c = ref text[0];
}

这种限制是否有任何隐藏的技术原因?为什么C#不支持这一点?(完成了吗?(

从技术上讲,因为字符串的索引器返回char,而ReadOnlySpan<T>的索引器则返回ref readonly T

其中一个原因是ref readonly返回仅添加到C#7.2中的语言中,该版本与引入ReadOnlySpan<T>的版本相同。然而,string自C#1以来就一直使用该语言。改变字符串的索引器返回的内容,使其返回ref readonly char而不是char,这将是一个突破性的更改。

更实际地说,将ref返回到char是毫无意义的:ref比char本身占用更多的内存!当您有一个大型结构,并且希望在不复制整个结构的情况下访问它的元素时,通常需要使用readonly refs。所以ref readonly SomeLargeStruct x = ref someReadOnlySpanOfSomeLargeStruct[0]

最新更新