Creating a cloned copy of subclass from baseclass

后端 未结 5 1749
鱼传尺愫
鱼传尺愫 2021-01-14 02:50

Consider this scenario:

public class Base
{
    public int i;
}

public class Sub : Base
{
    public void foo() { /* do stuff */}
}

And th

5条回答
  •  天命终不由人
    2021-01-14 03:08

    Well, since b isn't a Sub, we can't "clone" it as one.

    If Base has an appropriate combination of constructor and public properties to let a constructor in Sub ensure that its base would therefore have the same state as b, then we could use that.

    I think I'd by-pass the whole thing though. If all we care about is that s have the same state in its base as b, and it has not other state that we're going to care about (or else we'd have to be passing it through to the CloneAndUpcast method), then do we need s at all?

    A static method could take a Base and we could just use static public void foo(Base bc). We could even define it as an extension method static public void foo(this Base bc) and then code the call as b.foo(). The only thing this won't let us do that CloneAndUpcast() lets us do is access protected members.

提交回复
热议问题