C# virtual (or abstract) static methods

前端 未结 4 1948
孤独总比滥情好
孤独总比滥情好 2020-12-06 05:45

Static inheritance works just like instance inheritance. Except you are not allowed to make static methods virtual or abstract.

class Program {
    static vo         


        
4条回答
  •  情歌与酒
    2020-12-06 06:25

    Ok here is what I have done

    public abstract class Base
        where T : Base, new()
    {
        #region Singleton Instance
        //This is to mimic static implementation of non instance specific methods
        private static object lockobj = new Object();
        private static T _Instance;
        public static T Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (lockobj)
                    {
                        if (_Instance == null)
                        {
                            _Instance = new T();
                        }
    
                    }
                }
                return _Instance;
            }
        }
    
        #endregion //Singleton Instance
    
        #region Abstract Definitions
    
        public abstract T GetByID(long id);
        public abstract T Fill(SqlDataReader sr);
    
        #endregion //Abstract Definitions
    }
    
    public class InstanceClass : Base
    {
        //empty constructor to ensure you just get the method definitions without any
        //additional code executing
        public InstanceClass() { }
    
    
        #region Base Methods
    
        public override InstanceClass GetByID(long id)
        {
            SqlDataReader sr = DA.GetData("select * from table");
            return InstanceClass.Instance.Fill(sr);
        }
    
        internal override InstanceClass Fill(SqlDataReader sr)
        {
             InstanceClass returnVal = new InstanceClass();
             returnVal.property = sr["column1"];
             return returnVal;
        }
    }
    

    I think this will be a viable solution for what you want to do without breaking too many purist OO principles.

提交回复
热议问题