代码之家  ›  专栏  ›  技术社区  ›  Fatemeh Rostamipour

我无法在Program.cs中实例化我的学生类

  •  0
  • Fatemeh Rostamipour  · 技术社区  · 1 年前

    我的控制台应用程序中有一个学生类,如下所示:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
        public class Student
        {
            public Student(Student student)
            {
                StudentId = student.StudentId;
                FullName = student.FullName;
            }
    
            public int StudentId { get; set; }
            public string FullName { get; set; }
            
        }
    }
    

    它的主体中有一个复制构造函数,当我想在Program类中实例化它时,如下所示:

    Student student = new Student();
    

    我会有一个错误

    “没有给出与所需形式相对应的论点 “student”的参数“student”。学生(学生)'”

    当我不能实例化我的Student类时,我如何将Student的参数传递给它的构造函数?

    我想实例化我的学生类,但我遇到了我描述的错误。

    1 回复  |  直到 1 年前
        1
  •  2
  •   wohlstad    1 年前

    您提到要使用复制构造函数来创建新的 Student .

    这需要您有一个现有的 大学生 要从中复制的实例。

    此外,只要你只有一个复制构造函数,你就永远无法创建这样的实例(因为隐式默认构造函数将不再可用)。

    解决方案是添加一个构造函数-要么是默认的构造函数(没有参数),要么是需要例如 int 和一个 String 并初始化新实例的字段:

    // Default constructor:
    public Student()
    {
       StudentId = -1;        // some default ID
       FullName = "SomeName"; // some default name
    }
    

    // Constructor with parameters:
    public Student(int id, String name)
    {
       StudentId = id;
       FullName = name;
    }
    

    (甚至两者兼而有之)。
    请注意,如果您使用默认构造函数,您可能应该在之后将字段设置为正确的值。

    只有在使用这样的构造函数创建实例后,才能使用复制构造函数:

    // Create a default instance and then set the fields:
    Student studentToCopyFrom = new Student();
    studentToCopyFrom.StudentId  = 111;
    studentToCopyFrom.FullName = "Joe";
    // Or create an instance with arguments for the fields:
    Student studentToCopyFrom = new Student(111, "Joe");
    
    // Now create a new instance with the copy constructor:
    Student student = new Student(studentToCopyFrom);
    
        2
  •  1
  •   Agota Kristof    1 年前

    一旦你写了某种构造函数——在你的例子中是复制构造函数, 则删除默认构造函数, 因此,当您这样做时: Student student = new Student(); 它没有可引用的空构造函数。 您的解决方案是简单地创建一个默认构造函数,该构造函数使用您选择的默认值初始化参数

    public Student()
        {
            StudentId = 0;//for example
            FullName = "Jhon Doe";//for example
        }
    
        3
  •  1
  •   marsze    1 年前

    如果需要复制构造函数,请使用 record 类型,默认情况下已经有一个:

    public record class Student(int StudentId, string FullName);
    

    用法示例:

    var student2 = student1 with { StudentId = 42 };
    
    推荐文章