Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

c# - There is no argument given that corresponds to the required formal parameter 'name' of 'Employee.Employee(string,string, int)'

I have this Employee class:

public class Employee
{
    public string Name { get; set; }
    public string DateOfBirth { get; set; }
    public int PhoneNumber { get; set; }

    
    public Employee(string name, string dateOfBirth, int phoneNumber)
    {
        this.Name = name;
        this.DateOfBirth = dateOfBirth;
        this.PhoneNumber = phoneNumber;

    }
}

In this program:

namespace modelMIP
{
    
    class Program
    {
        static void Main(string[] args)
        {
            var angajat = new Employee()
            {
                Name = "ion",
                DateOfBirth = "28",
                PhoneNumber = 0770335978
                
            };
            Console.WriteLine(angajat); 
        }
        
    }
        
}

i have to create a ToString method for showing an object in this format : Name | DateOfBirth | PhoneNumber can anyone help me? what is the problem ?

question from:https://stackoverflow.com/questions/65940737/there-is-no-argument-given-that-corresponds-to-the-required-formal-parameter-na

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Employee constructor takes three arguments, but you're not passing any: new Employee().

You could simply change your initializers to passed constructor arguments:

            var angajat = new Employee("ion", "28", 0770335978);

If you like having the properties named, you can use parameter names:

var angajat = new Employee(
    name: "ion", 
    dateOfBirth: "28", 
    phoneNumber: 0770335978);

Or you could give your Employee class a constructor that takes no arguments, and rely on users to initialize properties they want to initialize.

    public Employee()
    {
    }

This latter would be more dangerous in some ways because people could easily forget to initialize the values.

You may also want to consider using C# 9's new record feature.

public record Employee(string Name, string DateOfBirth, int PhoneNumber);
    var angajat = new Employee(
        Name: "ion",
        DateOfBirth: "28",
        PhoneNumber: 0770335978);

The ToString() method, in either case, can look like this:

    public override string ToString() => $"{Name} | {DateOfBirth} | {PhoneNumber}";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...