日期:2014-05-18  浏览次数:20807 次

可以把父类中字段的值直接赋给子类吗
比如我有两个类:
C# code

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";
         
     }
}





------解决方案--------------------
User admin1 = admin;
admin1.name = "admin1";
之后原先 admin1 这个对象就没有了。

后面的问题一样。

你觉得 Guest guest1 = guest; 是又创建了一个 Guest 对象,复制了前面的,实际上没有!

先不要研究继承,你连对象都没搞清楚呢。

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"; // 此时 guest1 guest2 guest 是一个对象,ip 都是 192.168.168.5
------解决方案--------------------
C# code

// 首先,提个小小的建议: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