Can't define static abstract string property

后端 未结 5 1122
别跟我提以往
别跟我提以往 2021-02-19 10:03

I\'ve run into an interesting problem and am looking for some suggestions on how best to handle this...

I have an abstract class that contains a static method that accep

5条回答
  •  醉酒成梦
    2021-02-19 10:56

    Ok, this is not exactly to create an static abstract property, but you can achieve the desired effect.

    You can get this by using generics:

    public abstract class MyAbstractClass
    {
        public static string MyAbstractString{ get; set; }
        public static string GetMyAbstracString()
        {
    
            return "Who are you? " + MyAbstractString;
    
        }
    }
    
    public class MyDerivedClass : MyAbstractClass
    {
        public static new string MyAbstractString
        { 
            get 
            { 
                return MyAbstractClass.MyAbstractString; 
            }
            set
            {
                MyAbstractClass.MyAbstractString = value;            
            }
        }
    
    }
    
    
    public class MyDerivedClassTwo : MyAbstractClass
    {
        public static new string MyAbstractString
        {
            get
            {
                return MyAbstractClass.MyAbstractString;
            }
            set
            {
                MyAbstractClass.MyAbstractString = value;
            }
        }
    
    }
    
    
    public class Test
    {
    
        public void Test()
        {
    
            MyDerivedClass.MyAbstractString = "I am MyDerivedClass";
            MyDerivedClassTwo.MyAbstractString = "I am MyDerivedClassTwo";
    
    
            Debug.Print(MyDerivedClass.GetMyAbstracString());
            Debug.Print(MyDerivedClassTwo.GetMyAbstracString());
    
    
        }
    
    }
    

    So, calling the test class you will get:

    "Who are you? I am MyDerivedClass" "Who are you? I am MyDerivedClassTwo"

    So, you have an static method in an abstract class but the abstract value is different for each derived class, nice :D

    Ok, so, what's going here? The trick is the generic tag, the compiler is generating a different abstract class for each derived type.

    As I said it's not an abstract property, but you get all benefits of abstract static properties, which are programming static functions on your abstract class but using different static parameters per type.

提交回复
热议问题