What actually happens when I perform a suppression?

How exactly does it work?

If I have this base class

public class BaseClass
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }

    public BaseClass SimpleClone()
    {
        BaseClass result = new BaseClass();
        result.Value1 = this.Value1;
        result.Value2 = this.Value2;
        return result;
    }
}

And this child class

public class DerivedClass : BaseClass
{
    public bool Value3 { get; set; }

    public DerivedClass()
    {
        Value3 = true;
    }
}

How can I drop BaseCast.SimpleClone()in anotherObj? What will happen to Value3? Although knowing what is going on is good, I am also interested in why it works this way.

+4
source share
4 answers

The question as such does not make sense. There is no way for downcasting, because your clone method already returns the base class. I think you want (should) want to override the clone method in your subclass here:

public class DerivedClass : BaseClass
{
    //... Other stuff
    public BaseClass SimpleClone()
    {
        var result = new DerivedClass 
                         {
                             Value1 = this.Value1,
                             Value2 = this.Value2,
                             Value3 = this.Value3,
                         }
        return result;
    }

, DerivedClass , , DerivedClass - . , . , , : " , , BaseClass, DerivedClass". , , .

+2

, : ,

DerivedClass derived = (DerivedClass)baseObj.SimpleClone();

? InvalidCastException, BaseClass DerivedClass.

. .

+5

downcast - , SriRam. , , . , , :

public class BaseClass
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }

    protected virtual BasedClass Create()
    {
       return new BaseClass();
    }

    public virtual BaseClass SimpleClone()
    {
        var clone = Create(); // The appropriate create will be called
        clone.Value1 = this.Value1;
        clone.Value2 = this.Value2;
        return clone;
    }
}

public class DerivedClass : BaseClass
{
    public bool Value3 { get; set; }

    public DerivedClass()
    {
        Value3 = true;
    }

    protected override BasedClass Create()
    {
       return new DerivedClass();
    }

    public override BaseClass SimpleClone()
    {
       var result = base.SimpleClone();
       (result as DerivedClass).Value3 = this.Value3;
    }
}
+2

. - , , .

, , , .

, InvalidCastException.

+1

Source: https://habr.com/ru/post/1540091/


All Articles