zoukankan      html  css  js  c++  java
  • 原型模式中将父类强转为子类为什么不会报错呢?

    刚看到《大话设计模式》中的讲原型模式的一个Demo,其中有将父类对象强转为子类对象,理论上是不可以的,而且我写了个Demo测试也是不可以,但是我运行书上的Demo却能跑过去,让我很不解,希望能有人帮忙解释下原由,代码贴在下面:

    Code
     class Program
        {
            
    static void Main(string[] args)
            {
                Resume a 
    = new Resume("大鸟");
                a.SetPersonalInfo(
    "","29");
                a.SetWorkExperience(
    "2008-2009","华为");
                Resume b 
    = (Resume)a.Clone();
                
    //Resume c = (Resume)(new object());
                b.Display();
                Console.Read();



             
            }
        }

        
    class Resume:ICloneable
        {
            
    private string name;
            
    private string sex;
            
    private string age;
            
    private string timeArea;
            
    private string company;

            
    public Resume(string name)
            {
                
    this.name = name;
            }
            
    public void SetPersonalInfo(string sex, string age)
            {
                
    this.age = age;
                
    this.sex = sex;
            }
            
    public void SetWorkExperience(string timeArea, string company)
            {
                
    this.timeArea = timeArea;
                
    this.company = company;
            }

            
    public void Display()
            {
                Console.WriteLine(
    "{0}{1}{2}", name, sex, age);
                Console.WriteLine(
    "{0}{1}", timeArea, company);
            }

            
    #region ICloneable 成员

            
    public object Clone()
            {
                
    return (object)this.MemberwiseClone();
            }

            
    #endregion
        }

    如果我把注释部分运行起来,就会报无法将类型为“System.Object”的对象强制转换为类型。

    a.clone()返回的其实也是个object对象,为什么 Resume b = (Resume)a.Clone();是对的,而Resume c = (Resume)(new object());却运行时报错呢?

    不解...

  • 相关阅读:
    自己感受,如何解读别人的好的PHP代码
    34. RunAs Authentication Replacement运行身份验证替换
    32.3.3 Authenticating to a Stateless Service with CAS(使用CAS向无状态服务进行身份验证)
    33.2 Adding X.509 Authentication to Your Web Application
    35.2 Encryptors加密器
    32.3.2 Single Logout(单点退出)
    33. X.509 Authentication
    34.2 Configuration
    32.3.4 Proxy Ticket Authentication代理票证认证
    35.3 Key Generators密钥生成器
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/1503931.html
Copyright © 2011-2022 走看看