Best way to create instance of child object from parent object

前端 未结 7 583
萌比男神i
萌比男神i 2020-12-11 00:04

I\'m creating a child object from a parent object. So the scenario is that I have an object and a child object which adds a distance property for scenarios where I want to s

7条回答
  •  情深已故
    2020-12-11 00:45

    A generic solution would be to serialize it to json and back. In the json-string is no information about the class name from which it was serialized. Most people do this in javascript.

    As you see it works well for pocco objects but i don't guarantee that it works in every complex case. But it does event for not-inherited classes when the properties are matched.

    using Newtonsoft.Json;
    
    namespace CastParentToChild
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var p = new parent();
                p.a=111;
                var s = JsonConvert.SerializeObject(p);
                var c1 = JsonConvert.DeserializeObject(s);
                var c2 = JsonConvert.DeserializeObject(s);
    
                var foreigner = JsonConvert.DeserializeObject(s);
    
                bool allWorks = p.a == c1.a && p.a == c2.a && p.a == foreigner.a;
                //Your code goes here
                Console.WriteLine("Is convertable: "+allWorks + c2.b);
            }
        }
    
        public class parent{
            public int a;
        }
    
        public class child1 : parent{
         public int b=12345;   
        }
    
        public class child2 : child1{
        }
    
        public class NoFamily{
            public int a;
            public int b = 99999;
        }
    
        // Is not Deserializeable because
        // Error 'NoFamily2' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type 'NoFamily2' could be found (are you missing a using directive or an assembly reference?)
        public class NoFamily2{
            public int b;
        }
    }
    

提交回复
热议问题