簡體   English   中英

顯式實現接口時如何訪問static接口成員

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

我想知道我是否找到了正確的解決方案,如何在顯式實現接口時訪問接口的 static 屬性/方法。

在.NET 7個接口中可以定義static個抽象成員。 例如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方法是唯一的解決方案(不使用反射)還是我遺漏了什么?

這在對接口中 static 抽象成員提案的評論中進行了討論——目前除了通用間接(即GetOne<T>()方法)或對顯式實現的 static 抽象接口成員使用反射之外沒有其他選項。

只是為了完整性 - 使用反射(不完美地按成員名稱搜索)方法:

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