How to implement virtual static properties?

前端 未结 3 1489
粉色の甜心
粉色の甜心 2020-11-30 13:51

As far as I know C# doesn\'t support virtual static properties. How to implement such a behavior in C#?

I want to archive that all derived

3条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 14:34

    Another way to do this that doesn't require a class to be registered but does require a little extra work is to create a static class that holds the "static" data for each derived class type and return a constant/static value from the static class. Let me explain the specifics of this approach.

    One big reason for having a static property that is always the same for every member of the class is to avoid unnecessary memory use and repetition. While the method demonstrated here doesn't avoid this entirely, it still bypasses most of the "extra" overhead. The only use case that the example below will not satisfy is if the reason for using a static property is so that you don't have to have an instance since you must have an instance to get to the data.

    If you need a virtual field or property that is always the same for each member of the class (static), use a non-static property that returns a "constant" or static data like this:

    public static class MyStaticData
    {
        public static const string Class1String = "MyString1";
        public static const int Class1Int = 1;
        public static const string Class2String = "MyString2";
        public static const int Class2Int = 2;
        // etc...
    }
    
    public abstract class MyBaseClass
    {
        public abstract string MyPseudoVirtualStringProperty { get; }
        public abstract int MyPseudoVirtualIntProperty { get; }
    }
    
    public class MyDerivedClass1 : My BaseClass
    {
        public override string MyPseudoVirtualStringProperty { get { return MyStaticData.Class1String; } }
        public override int MyPseudoVirtualIntProperty { get { return MyStaticData.Class1Int } }
    }
    
    public class MyDerivedClass2 : My BaseClass
    {
        public override string MyPseudoVirtualStringProperty { get { return MyStaticData.Class2String; } }
        public override int MyPseudoVirtualIntProperty { get { return MyStaticData.Class2Int } }
    }
    

提交回复
热议问题