首页 > 解决方案 > 如何在 C# 中复制对象?

问题描述

我必须在 asp.net 网页中使用 c# 做一个重复按钮,这让我很伤心,因为我从微软网站https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/找到了一些文档classes-and-structs/how-to-write-a-copy-constructor,但不知何故仍然不知道如何使它在我的项目中工作。我试图在我的模型项目中编写一个复制构造函数,其中有我的类和属性:

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        //Instance constructor.
        public Person()
        {
        }
        //Copy constructor.
        public Person(Person previousPerson)
        {
            Name = previousPerson.Name;
            Age = previousPerson.Age;
        }
}

然后我有我想要显示表单的内容页面:

@using ClassLibrary1
@{

    if (IsPost)
    {
        Person person = new Person();


        if (Validation.IsValid())
        {
            switch (Request.Form["action"])
            {
                case "Submit":
                    person.Name = Request.Form["Name"];
                    person.Age = Request.Form["Age"].AsInt();
                    break;
                case "Duplicate":
                    Person person1 = new Person(person);
                    person1.Name = Request.Form["Name"];
                    person1.Age = Request.Form["Age"].AsInt();
                    break;
            }
        }
    }
}
<form method="post">
    <fieldset>
        <legend>Add Customer</legend>
        <div>
            <label for="Name">Name:</label>
            <input type="text" name="Name"
                   value="@Request.Form["Name"]" />
        </div>
        <div>
            <label for="Age"> Age:</label>
            <input type="text" name="Age"
                   value="@Request.Form["Age"]" />
        </div>
        <button name="action" value="Save" type="submit">Save</button>
        <button name="action" value="Duplicate" type="submit">Duplicate</button>
    </fieldset>
</form>

我想让用户完成form,当他们按下保存按钮时,form将被提交。我的问题是当我想复制表单并对其进行深层复制时form。我错过了一些东西,我不知道是什么。任何想法?顺便一提。我祝福你有个美好的一天。

标签: c#asp.net-webpages

解决方案


推荐阅读