开发者

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

I want to set "person" properties of studen开发者_JAVA技巧t1 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜