当接口被显式实现时,如何访问静态接口成员

5
我在想我是否找到了一种正确的方法来访问显式实现接口的静态属性/方法。
在.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方法是唯一的解决方案吗?或者我漏掉了什么?


好问题。我也在想明确接口实现背后的设计决策。 - Good Night Nerd Pride
好问题!我也被没有一种“干净”的方式来访问接口静态成员所困扰。 - undefined
1个回答

3

这个问题在评论中讨论过,是关于接口中静态抽象成员的提案 - 目前除了通用间接方式(即GetOne<T>()方法)或使用反射来显式实现静态抽象接口成员之外,没有其他选项。

只是为了完整性 - 使用反射(通过成员名称进行不完美搜索)的方法:

var properties = typeof(int).GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
var propertyInfo = properties.FirstOrDefault(t => t.Name.EndsWith(".One"));
var one = (int)propertyInfo.GetValue(null);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接