Override a Property with a Derived Type and Same Name C#

前端 未结 5 909
臣服心动
臣服心动 2020-12-29 11:21

I\'m trying to override a property in a base class with a different, but derived type with the same name. I think its possible by covarience or generics but am not sure how

5条回答
  •  梦毁少年i
    2020-12-29 11:37

    Not sure about Generics, but you could achieve a limited effect with simple Polymorphism (assuming SunData inherits from Data etc)

    public class Sun : OuterSpace 
    {
      void SomeInitializationMethod()
      {
        Data = new SunData();
        Analysis = new SunAnalysis(); // etc
      }
    
        }
    
    // You could also make casting simpler with a generic method on the base
    public T GetData()
    {
      if (Data is T)
      {
        return Data as T;
      }
      return null;
    };
    

提交回复
热议问题