我们可以创建一个参数化的类构造函数以在 C# 中实现相同的目标。我们可以将先前的类对象传递给新类对象的构造函数,并从中复制所有值。以下代码示例向我们展示了如何使用 C# 中的参数化构造函数方法创建类对象的单独副本。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace copy_an_object
{
    class MyClass
    {
        public String test;
        public MyClass()
        {
        }
        public MyClass(MyClass other)
        {
            test = other.test;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass a = new myClass();
            a.test = "This is a test";
            MyClass b = new MyClass(a);
            b.test = "This is not a test";
            Console.WriteLine(a.test);
            Console.WriteLine(b.test);
        }
    }
}

输出:

This is a test
This is not a test
更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Fasty 微信支付

微信支付

Fasty 支付宝

支付宝

Fasty 贝宝

贝宝