我希望 Fullname
由 FirstName
和 Lastname
组成,但出现以下异常:
A field initializer cannot reference the non static field, method or property 'Employee.FirstName' / 'Employee.LastName'
class Employee
{
public string FirstName { get; }
public string LastName { get; }
private string FullName = string.Format("{0}, {1}", FirstName, LastName);
}
最佳答案
运行时不保证类字段的分配顺序。这就是编译器警告您编译时错误的原因。
如果 FullName
是公共(public)属性(property),您可以:
class Employee
{
public string FirstName { get; }
public string LastName { get; }
public string FullName => $"{FirstName} {LastName}";
}
对于不使用 C#-6 的人:
class Employee
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string FullName
{
get { return string.Format("{0} {1}", FirstName, LastName); }
}
}
或者,如果您不希望它公开,则需要通过类构造函数实例化这些字段
class Employee
{
public Employee(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
fullName = $"{FirstName} {LastName}";
}
public string FirstName { get; }
public string LastName { get; }
private string fullName;
}
关于c# - 我想要一个 String 字段由另外两个字段组成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33103102/