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

标签 c#

我希望 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/

相关文章:

c# - 企业库 5.0 强行关闭事件连接

c# - 数字格式 : how to convert 1 to "01", 2 到 "02"等?

c# - ASP.NET 中的安全 Cookie

c# - 使用 x :Static 向 xaml 中的数组添加值

c# - Xamarin表单-C#-异步和等待不起作用?

c# - 在 C# 和 Unity 中更改特定时间的文本颜色

c# - 如何像 Microsoft Word 一样在 TextBox 中给拼写错误的单词加下划线?

c# - 子查询,在 Select 内部,不将 Order By 应用于基础查询

c# - ASP.NET Core MVC View 组件搜索路径

c# - ViewPort3D:如何从后面的代码创建带有文本的 WPF 对象(立方体)