I want to make a contract about static methods/properties in order to use them in a generic setting. Like this:
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);
}
I would use it like this:
AnimalSoundExplainer<Dog>.Explain(); // should write "Every Dog makes woof"
AnimalSoundExplainer<Cat>.Explain(); // should write "Every Cat makes meow"
How can I make that contract (so that I get compile errors if I do not fulfill the contract)? C#'s static interface members do not work that way; C# will always just use the (provided or not) implementation of
IAnimal
. It does allow implementing/overriding static members analog to non-static members.How can I make use of that contract inside a generic setting, i.e. how can I access theses members from a given generic type argument
- without needing to generate instances and
- without using reflection methods that make my program slow? (If there are reflection methods that do not make my program slow, I'd be okay with them.)
CodePudding user response:
This functionality is called "static abstract members", and it is currently in preview in .NET 6.
If you're happy enabling preview functionality, the following works in .NET 6 preview:
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);
}