gpt4 book ai didi

c# - Any() 不在可移植类库中编译;有其他选择吗?

转载 作者:太空宇宙 更新时间:2023-11-03 21:12:38 25 4
gpt4 key购买 nike

如何将以下语句移植到 PCL?

using System.Linq;

string value = ...;

if (value.Any(ch => ch > Byte.MaxValue)) {
throw new ArgumentException("String contains non-ASCII characters.", "value");
}

上面的代码无法编译,我总是收到以下错误消息:

Error   CS1061  'string' does not contain a definition for 'Any' and no
extension method 'Any' accepting a first argument of type 'string' could be
found (are you missing a using directive or an assembly reference?)

最佳答案

看起来像 string.GetEnumerator() is not supported in the PCL .因此 IEnumerable<char> 的隐式实现也不是。

您可以通过以下操作轻松获得应该支持 linq 的字符数组

if (value.ToCharArray().Any(ch => ch > Byte.MaxValue)) {
throw new ArgumentException("String contains non-ASCII characters.", "value");
}

我会注意到,如果创建了很多无关数组,可能会存在性能问题。如果您可以测量由此引起的性能问题,则较低级别的方法是:

for(int i=0; i < value.Length; i++)
{
char ch = value[i];
if (ch > Byte.MaxValue))
{
throw new ArgumentException("String contains non-ASCII characters.", "value");
}
}

关于c# - Any() 不在可移植类库中编译;有其他选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36634416/

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