在get set函数中拆分字符串
本文关键字:拆分 字符串 函数 get set | 更新日期: 2023-09-27 18:29:22
我正试图找到一种方法,将传入的字符串自动拆分为一个解析良好的数组或列表。我的页面上有一个<textarea>
,它可以进行逗号分隔或空格分隔。该<textarea> will be filling my
multiChoiceOptions`。然后我想让我的get/set自动将字符串解析为字符串数组。
我走对了吗?
private string _options;
public string[] multiChoiceOptions
{
get {
this._options = splitString(this._options);
return this._options;
}
set {
this._options = value;
}
}
public string[] splitString(string value)
{
string[] lines = Regex.Split(value, "'r'n");
return lines;
}
我将使用一对属性,一个用于原始选项列表,另一个用于解析的数组。解析将在原始可选值的setter上完成。
由于设置选项的正确方法是使用源选项字符串,因此解析后的数组不需要setter。
private string[] z_multiChoiceOptions = null;
public string[] multiChoiceOptions
{
get
{
return this.z_multiChoiceOptions;
}
}
private string z_Options = null;
public string Options
{
get { return z_Options; }
set {
z_Options = value;
if (value != null)
this.z_multiChoiceOptions = Regex.Split(value, "'r'n");
else
this.z_multiChoiceOptions = null;
}
}
在代码中不可能将所有数组变量同时放在字符串变量中。
例如:在代码中存储数组的正确方法是。
private string _options;
private string[] newArray; //declare new array for storing array.
public string[] multiChoiceOptions
{
get {
this.newArray= splitString(this._options);
return this.newArray;
}
set {
this.newArray = value;
}
}
public string[] splitString(string value)
{
string[] lines = value.split(","); //use String.Split
return lines;
}
我在控制台应用程序中使用您的代码。
static void Main(string[] args)
{
string[] arrayEmpty = new string[]{}; //I use empty array cause I don't know what you want to do.
multiChoiceOptions = arrayEmpty;
}
private static string _options = "samle,sample";
private static string[] newArray;
public static string[] multiChoiceOptions
{
get
{
newArray = splitString(_options);
return newArray;
}
set
{
newArray = value;
}
}
public static string[] splitString(string value)
{
string[] lines = value.Split(','); //use String.Split
return lines;
}