是否有一种方法可以将模型的属性操作为另一个属性?
我需要生成FullName基于所提供的LastName和FirstName
public class User
{
public string Username { get; set; } = null!;
public string Role { get; set; } = null!;
public int EmployeeID { get; set; }
public string FullName { get; set; } = null!; //CONCAT FROM LastName & FirstName
public string LastName { get; set; } = null!;
public string FirstName { get; set; } = null!;
public Division Division { get; set; } = null!;
}
用public string FullName => LastName +" "+ FirstName;
代替public string FullName {get;set;}
同样,真的没有必要指定= null
作为引用类型属性的默认值——引用类型的默认值已经是null了。
尝试:
public string FullName
{
get { return string.Format("{0} {1}", FirstName, LastName); }
}
您可以通过使FullName
属性仅为getter来连接FirstName
和LastName
:
public string LastName { get; set; };
public string FirstName { get; set; };
public string FullName
{
get { return LastName + " " + FirstName; }
}