在 .NET Windows Store 应用中,似乎不能再将字符串作为可枚举对象使用。以下代码适用于桌面应用程序,但不适用于应用程序:
public static bool SolelyConsistsOfLetters(string s)
{
return s.All(c => char.IsLetter(c));
}
错误是
'string' 不包含 'All' 的定义,也没有接受类型 'string' 作为第一个参数的任何扩展方法 'All' 可用(是否缺少 using 指令或程序集引用?)
但我没有缺少程序集引用或 using System.Linq;
。以下代码可以运行:
public static IEnumerable<char> StringAsEnumerable(string s)
{
foreach (char c in s)
{
yield return c;
}
}
public static bool SolelyConsistsOfLetters(string s)
{
return StringAsEnumerable(s).All(c => char.IsLetter(c));
}
问题在于s as IEnumerable<char>
无法工作(错误:“无法将类型'string'转换为'System.Collections.Generic.IEnumerable'(..)”), 并且s.GetEnumerator()
不可用。
我的问题:
- 真的没有更优雅的方法可以使用字符串作为可枚举对象(不使用上述帮助方法)吗? 我觉得我一定漏掉了什么非常明显的东西。
- 由于字符串不像可枚举对象那样运行,为什么/如何在此处使用foreach?
s as IEnumerable<char>
无法工作”的意思是什么?它实际上是做了什么? - svickString.GetEnumerator
(请参阅String.GetHashCode
的相同页面)。我想编译器正在将foreach
优化为for
循环。 - RawlingGetEnumerator()
它不应该被编译。此外,似乎支持非泛型的GetEnumerator()
(http://msdn.microsoft.com/en-us/library/bb344612.aspx)。@Sebastians.Cast<char>().All(…)
可以工作吗? - svick