日期:2014-05-18 浏览次数:20807 次
public class User { public string name; public string desc; public string reark; } public class Guest: User { public string IPAddress; } public class Test() { public void t() { User admin = new User() { name = "admin", desc = "管理员", remark = "管理员"}; User admin1 = new User() { name = "admin1", desc = "管理员", remark = "管理员"} /*问题1:如果大多数属性一样,只有一个属性不一样。我想直接复制对象里的属性,然后再修改不一样的属性, 我可以这样写吗?如下:*/ User admin1 = admin; admin1.name = "admin1"; //问题二:我现在想通过子类去复制父类的属性,然后再增加自己的属性,可以吗?比如: User guest = new User() { name = "guste", desc = "游客", remark = "游客"}; Guest guest1 = guest; guest1.IPAddress = "192.168.168.3"; Guest guest2 = guest; guest1.IPAddress = "192.168.168.5"; } }
// 首先,提个小小的建议:public 变量改为属性比较好。 // 问题一:不能。你那样做是将 admin1 的变量引用指向了 admin 所指的对象。也就是说,admin1 和 admin 将指向同一个对象。如果需要这么做,可以自己实现一个 Copy 方法,或者实现 IClonable 接口,override 其中的 Clone 方法,具体实现大致一样: public class User { public string Name { get; set; } public string Desc { get; set; } public string Remark { get; set; } public virtual User Copy() { return new User() { Name = Name, Desc = Desc, Remark = Remark }; } public override string ToString() { return String.Format("Name = '{0}', Desc = '{1}', Remark = '{2}'", Name, Desc, Remark); } } // 测试代码: User admin = new User() { Name = "admin", Desc = "管理员", Remark = "管理员" }; User admin2 = admin.Copy(); admin2.Name = "admin2"; Console.WriteLine(admin); Console.WriteLine(admin2); // 问题二:不允许。无法从实际的父类对象强制转换成子类对象。但是,其实你可以定义一个构造函数: public class Guest : User { public string IPAddress { get; set; } public override string ToString() { return String.Format("{0}, IPAddress = '{1}'", base.ToString(), IPAddress); } public Guest(User user) { Name = user.Name; Desc = user.Desc; Remark = user.Remark; } } // 调用代码变得相当简单: User user1 = new User() { Name = "guste", Desc = "游客", Remark = "游客" }; Guest guest1 = new Guest(user1) { IPAddress = "192.168.1.1" };
------解决方案--------------------
http://blog.csdn.net/sandy945/article/details/7166091