.net c#并行继承

Parallel inheritance
2021-07-22
  •  译文(汉语)
  •  原文(英语)

我有对象BaseObject和DerivedObject.然后,我想给BaseObject一个BaseContainer,并给DerivedObject一个DerivedContainer.

(DerivedObject:BaseObject,DerivedContainer:BaseContainer)

例如,使用new关键字:

BaseObject:

公共BaseContainer容器{get; 放;}

DerivedObject:

public new DerivedContainer Container
{ 
  get { return (DerivedContainer)base.Container; }
  set { base.Container = value;
        //Some extra things that MUST be called
      }
}

virtual并且override不起作用,因为您无法更改返回类型(get;失败). new如果这样做((BaseObject)myDerivedObject).Container = something,则无法正常工作,因为它没有在中调用额外的代码(注释部分)DerivedObject.Container__set.

我知道我可以将属性设置为get-only,use new,并添加一个虚拟的setter方法(返回类型始终为空,因此我可以覆盖它),但是我想知道是否有解决方法.

解决过程1

您可以使用泛型.

class Base<TContainer> where TContainer : Container
{
    TContainer Container { get; set; }
}

class Derived : Base<DerivedContainer> { }

I have objects BaseObject and DerivedObject. Then I want to give BaseObject a BaseContainer, and give DerivedObject a DerivedContainer.

(DerivedObject : BaseObject, DerivedContainer : BaseContainer)

For example, using the new keyword:

BaseObject:

public BaseContainer Container {get; set;}

DerivedObject:

public new DerivedContainer Container
{ 
  get { return (DerivedContainer)base.Container; }
  set { base.Container = value;
        //Some extra things that MUST be called
      }
}

virtual and override won't work, because you can't change the return type (get; fails). new doesn't work if I do ((BaseObject)myDerivedObject).Container = something, because it's not calling the extra code (the comment part) in DerivedObject.Container__set.

I know I can make the property get-only, use new, and add a virtual setter method (return type is void anyways, so I can override it), but I was wondering if there was any way around this.

Solutions1

You could use generics.

class Base<TContainer> where TContainer : Container
{
    TContainer Container { get; set; }
}

class Derived : Base<DerivedContainer> { }
转载于:https://stackoverflow.com/questions/17397352/parallel-inheritance

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入