gpt4 book ai didi

c# - 是否可以创建一个由其他属性组合而成的类属性?

转载 作者:行者123 更新时间:2023-11-30 13:10:30 26 4
gpt4 key购买 nike

我想将一些字符串属性组合成一个字符串,以便于排序和显示。我想知道是否有一种方法可以做到这一点而不必遍历类的集合或列表。类似于下面 Person 类中的 FullName。

public class Person
{
public string Last {get;set;}
public string First {get;set;}

public string FullName = Last + ", " + First {get;}
}

最佳答案

像这样更新你的类:

public class Person
{
public string Last { get; set; }
public string First { get; set; }

public string FullName
{
get
{
return string.Format("{0}, {1}", First, Last);
}
}
}

除了你的问题,我还建议实现 ToString() 方法的重写(你的问题提到使显示更容易),因为大多数 UI 技术将使用它作为显示对象。

public override string ToString()
{
return FullName;
}

关于c# - 是否可以创建一个由其他属性组合而成的类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12554101/

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