Вопрос

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?

Это было полезно?

Решение

  1. There is only one instance of the field Animal.Name. There is no separate Cat.Name.

    This implies that Cat.Name and Animal.Name will always return the same value, either Cat or Animal depending on which static constructor was the most recent to run.

  2. 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 of Cat in this sense, since it's actually Animal.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.

Другие советы

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.

.NET Static Constructors on MSDN

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top