提问人:OndMal 提问时间:1/30/2023 最后编辑:OndMal 更新时间:1/31/2023 访问量:219
显式实现接口时如何访问静态接口成员
How to access static interface member when the interface is implemented explicitly
问:
我想知道我是否找到了正确的解决方案,如何在显式实现接口时访问接口的静态属性/方法。
在 .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。一个值。
这是我尝试过的:
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 方法是唯一的解决方案(不使用反射)还是我遗漏了什么?
答:
3赞
Guru Stron
1/30/2023
#1
这在接口中静态抽象成员提案的评论中进行了讨论 - 目前除了通用间接(即 approach) 或对显式实现的静态抽象接口成员使用反射。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);
评论