There is only one instance of the field
Animal.Name
. There is no separateCat.Name
.This implies that
Cat.Name
andAnimal.Name
will always return the same value, eitherCat
orAnimal
depending on which static constructor was the most recent to run.The static constructor hasn't run yet, so it's still returning the old name. The static constructor only runs when you access a static member of
Cat
(or construct an instance of it).Cat.Name
isn't a member ofCat
in this sense, since it's actuallyAnimal.Name
.The specifications says about when to run static constructors:
The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
· An instance of the class type is created.
· Any of the static members of the class type are referenced.
Static delegates and override
-
05-10-2022 - |
Frage
In one of my many attemts to find a good solution to static override in C# (it´s easy in objective-C, so don´t tell me that "it´s impossible", or that "only objects are polymorphic" because I know) I tried an approach with delegates. My code is:
public class Animal
{
public static Func<string> Name { get; protected set; }
static Animal()
{
Name = () => "Animal";
}
}
public class Cat : Animal
{
static Cat ()
{
Name = () => "Cat";
}
}
But when I call Cat.Name()
I still get "Animal". I am not asking for a solution, I am asking: why?
Lösung
Andere Tipps
There is no inheritance of static methods in .NET. In terms of IL, Cat.Name
does not exist, however .NET allows you to call the base class' method from the subclass.
That explains why the static Cat
constructor is never called.
As Name
is a method of Animal
and not of Cat, Animal.Name
is triggered and hence, Animal's
constructor will be run. The result: you're an animal, not a cat.