Casting between two types derived from the (same) interface

前端 未结 9 2033
南方客
南方客 2020-12-20 12:55

I have an interface and two types that derive from it.

However, I cannot do the following:

B objectB = (B) objectA

Where B derives

9条回答
  •  执念已碎
    2020-12-20 13:26

    Imagine the following setup:

    public interface Human
    {
        bool Male { get; }
    }
    
    public class Man : Human
    {
        public bool HasABeard { get { return true; } }
    
        public bool IsMale { get { return true; } }
    }
    
    public class Woman : Human
    {
        public bool IsMale { get { return false; } }
    
        public List> Shoes { get; set; }
    }
    

    What would you expect the compiler to produce from the following code? What will the output be?

    Man a;
    Woman b = new Woman();
    a = (Man)b;
    
    Console.WriteLine(a.HasABeard ? "Beard ON" : "Beard OFF");
    

提交回复
热议问题