Ond*_*Mal 5 c# methods static interface abstract
我想知道当接口显式实现时,我是否找到了如何访问接口的静态属性/方法的正确解决方案。
在.NET 7接口中可以定义静态抽象成员。例如System.Numerics.INumberBase接口定义:
public static abstract TSelf One { get; }
Run Code Online (Sandbox Code Playgroud)
该接口由各种数字类型显式实现,例如System.Int32。
/// <inheritdoc cref="INumberBase{TSelf}.One" />
static int INumberBase<int>.One => One;
Run Code Online (Sandbox Code Playgroud)
现在尝试访问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;
}
Run Code Online (Sandbox Code Playgroud)
GetOne方法是唯一的解决方案(不使用反射)还是我遗漏了什么?
这在接口中静态抽象成员提案的评论中进行了讨论- 目前,除了通用间接(即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);
Run Code Online (Sandbox Code Playgroud)