我在构建netcoreapp
代码时遇到错误,我无法解决netstandard
。
以下代码在netcoreapp2.2
中编译:
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace TestNamespace
{
public class TestClass
{
public static Group Example(string str, string pattern) =>
Regex.Match(str, pattern).Groups.First();
}
}
但是如果我将其更改为netstandard2.0
则.First
将无法编译:
Class1.cs(10, 46): [CS1061] 'GroupCollection' does not contain a definition for 'First' and no accessible extension method 'First' accepting a first argument of type 'GroupCollection' could be found (are you missing a using directive or an assembly reference?)
但是,如果我在 Jetbrains Rider 中使用"转到代码",GroupCollection
的反汇编将解析为实现IList
的System.Text.RegularExpressions, Version=4.2.1.0
。我已经手动添加了此程序集并System.Linq
但错误仍然存在。
知道发生了什么吗?有什么修复的想法吗?
GroupCollection
在更高版本的 .NET Core 中实现IList<Group>
。IList<Group>
足以使 LINQ 扩展方法(如First
(正常工作。
.NET Framework(或早期版本的 .NET Core(中的GroupCollection
不实现该接口(它仅实现较旧的(非泛型(接口(。因此,如果不强制转换First
,就无法使用它。
如果您决定Cast
,那么相同的代码将适用于所有内容(.NET Core/Standard/Framework(。