繁体   English   中英

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

[英]Is it possible to create a class property that is a combination of other properties?

我想将几个字符串属性组合成一个字符串,以便于排序和显示。 我想知道是否有一种方法可以做到这一点而不必遍历类的集合或列表。 下面的 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;
}
public string FullName {
  get{
    return Last + ", " + First;
  }
}

当然:

public string FullName 
{
    get
    {
        return FirstName + ", " + LastName;
    }
}

为什么不?

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

试试这个:

  public string FullName 
     {
          get
            {
                return Last + " " + First;    
            }        
      }
public string Fullname
{
    get
    {
        return string.Format("{0}, {1}", Last, First);
    }
    set
    {
        string[] temp = value.Split(',');
        Last = temp[0].Trim();
        First = temp[1].Trim();
    }
}

是的。 您可以使用类中的属性来执行相同的操作。 甚至 Microsoft 也建议在类中创建一个 void 方法,该方法只是将类的字段作为属性而不是方法进行简单的操作。

使用字符串插值,因为它简单易行;)

    public class ApplicationUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }


        public string FullName
        {
            get
            {
                return $"{FirstName} {LastName}";
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM