Convert/Cast base type to Derived type

前端 未结 5 1611
Happy的楠姐
Happy的楠姐 2020-12-20 17:12

I am extending the existing .NET framework class by deriving it. How do I convert an object of base type to derived type?

public class Results { //Framework          


        
5条回答
  •  情深已故
    2020-12-20 17:34

    As earlier answers have said, you need to instantiate a new instance of MyResults then copy the properties over from your Results object. You asked what a "copy constructor" was - it is just a constructor that takes an object and uses it to populate the object being constructed. For example:

        public class Results
        {
            public string SampleProperty1 { get; set; }
            public string SampleProperty2 { get; set; }
        }
    
        public class MyResults : Results
        {
            public MyResults(Results results)
            {
                SampleProperty1 = results.SampleProperty1;
                SampleProperty2 = results.SampleProperty2;
            }
        }
    

    A copy constructor is usually more convenient, readable and reusable than using code like this:

    MyResults myResults = new MyResults
    {
        SampleProperty1 = results.SampleProperty1,
        SampleProperty2 = results.SampleProperty2
    };
    

    If there are lots of properties and/or you are making lots of changes to the class you could use reflection (e.g. C# Using Reflection to copy base class properties ) or a tool such as AutoMapper ( http://automapper.codeplex.com ) to copy the properties. But often that can be overkill.

提交回复
热议问题