Permanently cast derived class to base

前端 未结 6 1537
慢半拍i
慢半拍i 2020-12-09 16:19
Class A { }
Class B : A { }

B ItemB = new B();
A ItemA = (A)B;

Console.WriteLine(ItemA.GetType().FullName);

Is it possible to do something like a

6条回答
  •  醉梦人生
    2020-12-09 16:51

    For amusement, if you wanted to lose all of the derived data you could do this:

       class Program
        {
            [DataContract(Name = "A", Namespace = "http://www.ademo.com")]
            public class A { }
             [DataContract(Name = "A", Namespace = "http://www.ademo.com")]
            public class B : A  {
                 [DataMember()]
                 public string FirstName;
            }  
    
        static void Main(string[] args)
        {
            B itemB = new B();
            itemB.FirstName = "Fred";
            A itemA = (A)itemB; 
            Console.WriteLine(itemA.GetType().FullName);
            A wipedA = WipeAllTracesOfB(itemB);
            Console.WriteLine(wipedA.GetType().FullName);
        }
    
        public static A WipeAllTracesOfB(A a)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(A));
    
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, a);
                ms.Position = 0;
    
                A wiped = (A)serializer.ReadObject(ms);
    
                return wiped;
            }
        }
    }
    

    If you use the debugger you will see the FirstName is still stored in the field FirstName when it is cast to an A, when you get an A back from WipeAllTracesOfB there is no FirstName, or any trace of B.

提交回复
热议问题