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

前端 未结 5 921
臣服心动
臣服心动 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条回答
  •  一个人的身影
    2020-12-29 11:24

    It is not possible the way you want it, exactly.

    You can create a "new" property with the same name:

    public new SunData Data
    {
      get { return (SunData) base.Data; }
      set { base.Data = value; }
    }
    

    It's not quite the same thing, but it's probably as close as you're going to get.

    Another possible approach would be:

    public SunData SunData { get; set; }
    
    public override OuterSpaceData Data
    {
      get { return SunData; }
      set { SunData = (SunData)value; }
    }
    

    The advantage of this approach is that it does guarantee that it's impossible to put something in your Data property that is not a SunData. The downside is that your Data property is not strongly typed and you have to use the SunData property if you want it statically typed to SunData.

    There's an ugly way to get the "best of both worlds" at the expense of being confusing to code and difficult to understand afterwards - by introducing an intermediate derived class that does a 'sealed override' on the base class Data property and redirects to a different protected property with a new name, and then have the ultimate derived class add a 'new' Data property that then calls the intermediate property. It really is an ugly hack, though, and even though I've done it, I wouldn't recommend it.

提交回复
热议问题