简体   繁体   English

显式实现接口时如何访问static接口成员

[英]How to access static interface member when the interface is implemented explicitly

I wonder if I found the right solution how to access static property/method of the interface when the interface is implemented explicitly.我想知道我是否找到了正确的解决方案,如何在显式实现接口时访问接口的 static 属性/方法。

In .NET 7 interface can define static abstract members.在.NET 7个接口中可以定义static个抽象成员。 For example System.Numerics.INumberBase interface define:例如System.Numerics.INumberBase接口定义:

public static abstract TSelf One { get; } 

This interface is explicitly implemented by various numeric types, eg System.Int32 .该接口由各种数字类型显式实现,例如System.Int32

/// <inheritdoc cref="INumberBase{TSelf}.One" />
static int INumberBase<int>.One => One;

Now trying to access int.One value.现在尝试访问int.One值。

Here is what I tried:这是我尝试过的:

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;
}

Is the GetOne method the only solution (without using reflection) or am I missing something? GetOne方法是唯一的解决方案(不使用反射)还是我遗漏了什么?

This was discussed in the comments to the proposal for static abstract members in interfaces - currently there are no other options except for the generic indirection (ie GetOne<T>() approach) or using reflection for explicitly implemented static abstract interface members.这在对接口中 static 抽象成员提案的评论中进行了讨论——目前除了通用间接(即GetOne<T>()方法)或对显式实现的 static 抽象接口成员使用反射之外没有其他选项。

Just for completeness - using reflection (with not perfect search by member name) approach:只是为了完整性 - 使用反射(不完美地按成员名称搜索)方法:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM