我想就静态方法/属性签订合同,以便在通用设置中使用它们。像这样:
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"
我怎样才能签订合同(这样如果我不履行合同就会出现编译错误)?C# 的静态接口成员不能那样工作;C# 将始终只使用IAnimal
. 它确实允许实现/覆盖类似于非静态成员的静态成员。
如何在泛型设置中使用该契约,即如何从给定的泛型类型参数访问这些成员
此功能称为“静态抽象成员”,目前在 .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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句