gpt4 book ai didi

c# - 我想要一个 String 字段由另外两个字段组成

转载 作者:太空狗 更新时间:2023-10-30 00:10:10 24 4
gpt4 key购买 nike

我希望 FullnameFirstNameLastname 组成,但出现以下异常:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com