使用两个不同的公共属性来"获取"具有不同返回类型的相同私有变量

cor*_*ori 1 c# properties

我有一个Customer类,它有一个List <string> Roles属性.大部分的时间,我想访问该物业作为一个字符串列表,但有时我想看到它作为一个逗号分隔的列表.

我当然可以在一个新方法中做到这一点,如果我预计想要以不同的格式(逗号分隔,制表符分隔和&ct)获取变量的值,我肯定会这样做.但是,我正在考虑使用两个不同的属性来访问变量值,这有点像

public List<string> Roles 
{
    get { return this._Roles; }
    set { this._Roles = value; } 
}
Run Code Online (Sandbox Code Playgroud)

public string RolesToString
{
    get { do some work here to comma-delimit the list; }
}
Run Code Online (Sandbox Code Playgroud)

基本上我想覆盖此特定列表的ToString()方法.是否有令人信服的理由做一个超过另一个?是否使用两个不同的属性来返回相同的变量值足够非标准以引起红旗?

Ree*_*sey 10

我会让你的第二个"财产"成为一种方法.它在您的列表上执行其他处理,并返回不是对象的直接"属性"的内容,但更多是对象属性的已处理版本.这似乎是一个合理的候选方法.

我的偏好是:

public List<string> Roles 
{
    get { return this._Roles; }
    set { this._Roles = value; } 
}

public string GetRolesAsString()
{
    // Do processing on Roles
}
Run Code Online (Sandbox Code Playgroud)