我在想我是否找到了一种正确的方法来访问显式实现接口的静态属性/方法。
在.NET 7中,接口可以定义静态抽象成员。例如,System.Numerics.INumberBase 接口定义如下内容:
该接口由许多数字类型(例如 System.Int32)显式实现。
在.NET 7中,接口可以定义静态抽象成员。例如,System.Numerics.INumberBase 接口定义如下内容:
public static abstract TSelf One { get; }
该接口由许多数字类型(例如 System.Int32)显式实现。
/// <inheritdoc cref="INumberBase{TSelf}.One" />
static int INumberBase<int>.One => One;
现在尝试访问 int.One 的值。
这是我尝试过的:
using System;
public class Program
{
public static void Main()
{
// Does not compile - because One is implemented explicitly
// Compiler: 'int' does not contain a definition for 'One'
Console.WriteLine(int.One);
// Does not compile
// Compiler: A static virtual or abstract interface member can be accessed only on a type parameter.
Console.WriteLine(System.Numerics.INumberBase<int>.One);
// Compiles
Console.WriteLine(GetOne<int>());
}
private static T GetOne<T>() where T : System.Numerics.INumberBase<T> => T.One;
}
使用反射之外,GetOne方法是唯一的解决方案吗?或者我漏掉了什么?