如何通过接口调用抽象静态方法?

问题描述 投票:0回答:1

我正在寻找一种比反射更好的方法来调用一堆类上的静态方法。

假设我有一家工厂是这样播种的:

private static IReadOnlyDictionary<string, Type> buildableTypes =
  typeof(IBuildable).Assembly.GetTypes()
    .Where(t => t.IsSubclassOf(typeof(IBuildable)))
    .Where(t => !t.IsAbstract)
    .ToDictionary(t => t.Name, t => t);

并考虑 IBuildable 是这样的:

public interfact IBuildable
{
  static abstract bool IsBuildable(string params);
}

我想获取给定当前参数的所有可构建类型。

var currentlyBuildableTypes = buildableTypes.Values
    .Where(t => /* t.IsBuildable(params) */); // not sure what goes here

我想避免实例化每个类,因为可能会有相当多的数量。我可以很容易地通过反射来做到这一点,但考虑到 C# 11 中新的静态抽象接口,我希望有一种更优雅的方式来实现这一点。请注意,在这种情况下,使用泛型似乎也不是一种选择,因为直到运行时我才知道类型。

c# .net interface abstract
1个回答
0
投票

有时你只需要多介绍几种类型即可。

public interface IBuildable
{
    static abstract bool IsBuildable(string parms);
}
public abstract class BuildHelper
{
    public abstract Type Type { get; }
    public abstract bool IsBuildable(string parms);
}
public class BuildHelper<T> : BuildHelper
    where T : IBuildable
{
    public override Type Type 
        => typeof(T);
    public override bool IsBuildable(string parms)
        => T.IsBuildable(parms);
}
private static IReadOnlyDictionary<string, BuildHelper> buildableTypes =
   // TODO, left as an exercise for the reader
© www.soinside.com 2019 - 2024. All rights reserved.