只是一个警告,这个问题需要安装.NET 6的预览。
我试图在C#中创建一个接口,允许+操作符类似于在微软的INumber中实现它。
Interfaces.cs
using System;
using System.Runtime.Versioning;
namespace InterfaceTest;
[RequiresPreviewFeatures]
public interface IExtendedArray<T> : IAdditionOperators<IExtendedArray<T>, IExtendedArray<T>, IExtendedArray<T>>
where T : INumber<T>
{
Array Data { get; }
}
[RequiresPreviewFeatures]
public interface IExtendedFloatingPointArray<T> : IExtendedArray<T>
where T : IFloatingPoint<T>
{
}InterfaceTest.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<EnablePreviewFeatures>true</EnablePreviewFeatures>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>false</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Runtime.Experimental" Version="6.0.0-preview.7.21377.19" />
</ItemGroup>
</Project>但是,这段代码会产生
错误CS8920:接口'InterfaceTest.IExtendedArray‘不能用作泛型类型或方法'IAdditionOperators’中的类型参数'TSelf‘。约束接口'System.IAdditionOperators‘或其基接口具有静态抽象成员。
有办法用自定义类型来实现这一点吗?
dotnet --list-sdks显示我安装了6.0.100-rc.1.21458.32。但是我刚刚通过Visual 2022预览4安装了它。
发布于 2021-09-19 13:08:21
最后,我能够重现您的问题-需要安装VS 2022预览版(2019年版本编译代码很好,但在运行时失败)或使用终端dotnet build。
如果您想对INumber执行类似的操作,则需要使用TSelf类型引用遵循相同的模式(如果我没有弄错,则称为奇怪的是反复出现的模板模式):
[RequiresPreviewFeatures]
public interface IExtendedArray<TSelf, T> : IAdditionOperators<TSelf, TSelf, TSelf> where TSelf : IExtendedArray<TSelf, T> where T : INumber<T>
{
T[] Data { get; }
}
[RequiresPreviewFeatures]
public interface IExtendedFloatingPointArray<TSelf, T> : IExtendedArray<TSelf, T>
where TSelf : IExtendedFloatingPointArray<TSelf, T>
where T : IFloatingPoint<T>
{
}https://stackoverflow.com/questions/69238213
复制相似问题