将属性的返回类型更改为字符串数组:
public string UserName { get; set; }
public string[] UserNameSeparated
{
get { Username.Split('-'); }
set
{
UserName = String.Join("-", value);
}
}
用法:
foo.UserName = "10-1685";
string[] names = foo.UserNameSeparated;
// names[0] = "10";
// names[1] = "1685";
foo.UserNameSeparated = new string[] { "15", "42" };
// foo.UserName = "15-42"
但考虑对名称的两个部分都有属性。您将能够随时计算全名,并且您将处理好的命名属性而不是元组或数组索引(支持地狱):
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName
{
get { return String.Format("{0}-{1}", FirstName, LastName); }
set
{
// check if value format valid
var names = value.Split('-');
FirstName = names[0];
LastName = names[1];
}
}
只需比较(您可以提供更具描述性的名称,更好地描述您的数据):
foo.FirstName
foo.LastName
和:
foo.UserNameSeparated.Item1
foo.UserNameSeparated.Item2