如何在通用设置中使用类型(=静态)成员

how to use type (=static) members in a generic setting

我想就静态 methods/properties 签订合同,以便在通用设置中使用它们。像这样:

interface IAnimal {
    static string Sound;
}

class Dog : IAnimal {
    static string Sound => "woof";
}

class Cat : IAnimal {
    static string Sound => "meow";
}

class AnimalSoundExplainer<T> where T : IAnimal {

    // This does not work (but I would like it to):
    internal static void Explain() =>
        Console.WriteLine("Every " + typeof(T).Name + " makes " + T.Sound);
}

我会这样使用它:

AnimalSoundExplainer<Dog>.Explain(); // should write "Every Dog makes woof"
AnimalSoundExplainer<Cat>.Explain(); // should write "Every Cat makes meow"
  1. 我怎样才能订立合同(这样如果我不履行合同就会出现编译错误)? C# 的静态接口成员不是那样工作的; C# 将始终只使用(提供或不提供)IAnimal 的实现。它确实允许 implementing/overriding 类似于非静态成员的静态成员。

  2. 如何在通用设置中使用该契约,即如何从给定的通用类型参数访问这些成员

此功能称为“static abstract members", and it is currently in preview in .NET 6

如果您对启用预览功能感到满意,以下内容适用于 .NET 6 预览:

interface IAnimal {
    static abstract string Sound { get; }
}

class Dog : IAnimal {
    public static string Sound => "woof";
}

class Cat : IAnimal {
    public static string Sound => "meow";
}

class AnimalSoundExplainer<T> where T : IAnimal {

    internal static void Explain() =>
        Console.WriteLine("Every " + typeof(T).Name + " makes " + T.Sound);
}

See it on SharpLab.