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

条款

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

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. 它确实允许实现/覆盖类似于非静态成员的静态成员。

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

  • 无需生成实例和
  • 不使用使我的程序变慢的反射方法?(如果有反射方法不会让我的程序变慢,我会接受它们。)
第七州

此功能称为“静态抽象成员”,目前在 .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);
}

在 SharpLab 上查看

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章