简体   繁体   中英

what is the best practice of changing base object properties from inherited class

I want to set "person" properties of student1 to person1. Is this possible doing it with assigning or any way without setting properties one by one ?

static void Main(string[] args)
{
  var student1 = new Student {Id = 1, Name = "kaya", Class = "3b", Number = "156"};
            var person1 = new Person { Id = 2, Name = "hasan" };

        }


    public class Person
    {
        public int Id { get; set; }
        public String Name { get; set; }
    }

    public class Student : Person
    {
        public int Number { get; set; }
        public String Class { get; set; }
    }

Well you could do it with reflection - but I personally wouldn't. You could add a CopyTo method in Person :

public class Person
{
    public int Id { get; set; }
    public String Name { get; set; }

    public void CopyTo(Person other)
    {
        other.Id = Id;
        other.Name = Name;
    }
}

Another option would be to use composition instead of inheritance, such that a Student had a Person property instead of deriving from Person . It really depends on the bigger picture though - do you actually want a Student to be a specialized Person , or was it just a simple way of getting the data in there?

This sort of question comes up every so often, but I rarely find myself wanting to do it in my own code... I'd be interested to see the design of code which requires this, to work out how I'd have designed it instead. It's not clear to me whether this is just a matter of me not doing the kind of work which encourages this pattern, or whether I use alternative designs to solve the same problem.

Have you looked at AutoMapper? If you used half way decent conventions you end up writing almost zero code -

http://automapper.codeplex.com/

I recently used AutoMapper to map my POCOs with Subsonic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM