سؤال

The goal was to have a static member defined in a base class that, for each subclass that inherits from the base class, the static member would have different values (in this case, a list of the enumerable properties). I know that static members are static and so they "only exist once" and therefore can't have different values in base classes.

But I did come up with a way to make it look like it has different values.

Given this code:

public class Parent<TSelfReferenceType>
{
    public static readonly List<PropertyInfo> enumerableProperties
        = GetEnumerableProperties();

    public static Type GetTheType()
    {
        return typeof(TSelfReferenceType);
    }

    public static List<PropertyInfo> GetEnumerableProperties()
    {
        return GetTheType().GetProperties()
                           .Where(property => property.PropertyType.IsEnum)
                           .ToList();
    }
}

public class ChildA : Parent<ChildA>
{
    public EnumTypeOne ActivityType { get; set; }
    public EnumTypeTwo LogLevel { get; set; }
}

public class ChildB : Parent<ChildB>
{
    public EnumTypeThree Source { get; set; }
}

If I instantiate an instance of ChildA and ChildB, they each have a static enumerableProperties member with different values. Awesome!

The problem is that I don't really know what's going on under the covers. I know very little about inheritance with generics. Can somebody tell me what's going on to make this work this way?

هل كانت مفيدة؟

المحلول

You can understand generics as some kind of general template for separate types that all work the same but are different.

In your case, ChildA inherits from Parent<ChildA>, and ChildB inherits from Parent<ChildB>. The two parent types, Parent<ChildA> and Parent<ChildB>, are different though, so ChildA and ChildB do not have a common base type.

It is probably easier to understand, if you actually declare Parent<ChildA> and Parent<ChildB> as real separate types:

class Parent_ChildA { … }
class Parent_ChildB { … }

class ChildA : Parent_ChildA { … }
class ChildB : Parent_ChildB { … }

This is what really happens behind the scenes. So the two parent types are separate types, which also explains why they have separate static members. Two different classes wouldn’t share static members after all, even if they have the same name.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top