using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
// I am using structure to define values type set
public struct Employee
{
public int EmpId;
public string FirstName;
public string LastName;
// Here i am checking whether parameter less constructor will work
static Employee()
{
Console.WriteLine("First Object Created");
}
// Here i am using one more constructor for initializing it with some values later on
public void Employee(int number, string firsname, string lasname)
{
id = number;
FirstName = firsname;
LastName = lasname;
}
}
// Here i am using the parameterize constructor to assign values mentioned before in the //structure
class Program {
Employee emp1 = new Employee(23,"shiva","shankar");
}
}
//我得到的错误是Employee结构不包含需要3个参数的构造函数//名称ID在当前上下文中不存在///雇员:成员名称不能与其所在的类型相同
id
结构中没有Employee
字段,只有EmpId
。另外,C#中的constructor不能具有返回类型。
构造函数是一个名称与其名称相同的方法类型。它的方法签名仅包括方法名称及其参数表它不包含返回类型。
您应该按照以下方式重写代码
// Here i am using one more constructor for initializing it with some values later on
public Employee(int number, string firstName, string lastName)
{
EmpId = number;
FirstName = firstName;
LastName = lastName;
}
另外,将您的字段声明为私有或使用只读属性也很有意义
public int EmpId { get; }
public string FirstName { get; }
public string LastName { get; }
构造函数没有返回值。
public Employee(int number,字符串firsname,字符串lasname)