c# 通过构造函数及传入类对象方法参数来复制对象

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    public class Class1
    {
        public string name;
        public string sex;
        public Class1(string _name,string _sex)
        {
            name = _name;
            sex = _sex;
        }
    
        //此方法来复制同类的对象,其方法参数就是同类的对象
        public Class1 copylocal(Class1 c1)
        {
            //为构造函数的参数作准备初始化工作,这些数据源于copylocal
            //方法参数class c1
            name = c1.name;
            sex = c1.sex;
             //利用构造函数完成复制
            Class1 cc1 = new Class1(name,sex);
            //返回方法加工的类对象class cc1
            return cc1;
        }
        public void printnameandsex()
       {
           Console.WriteLine(name);
           Console.WriteLine(sex);
       }
      
    }
}
---调用
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;//arraylist派生于array类
namespace ConsoleApplication1
{
    class Program
    {
       //学习while
      public static void Main(string[] args)
      {
          Class1 c1 = new Class1("翟勋杨", "男");
          c1.printnameandsex();
         
          Class1 cx=c1.copylocal(c1);
          cx.printnameandsex();
          Console.ReadKey();
       }
    }
   
}
 
--输出:
翟勋杨
翟勋杨

 
请使用浏览器的分享功能分享到微信等