【发布时间】:2013-07-05 16:39:46
【问题描述】:
我在List<string> 上重复工作以构建MyClass 的实例,但为简单起见(涉及很多正则表达式和IndexOf 操作),我目前必须修剪每一行每次操作后:
static MyClass Populate (\List<str> strList)
{
MyClass myClassInstance = new MyClass();
Operation1(ref strList, myClassInstance);
TrimAllLines(strList);
Operation2(ref strList, myClassInstance);
TrimAllLines(strList);
//...
return myClassInstance;
}
有没有一种好方法(最好是直接替换),这样每次我写信给strList时,里面的每个字符串都会自动修剪?
我玩过的东西:
-
string的包装器,用于修剪隐式转换。会丢失字符串 Intellisense,并且IEnumerables 不会同样隐式转换。 - 使用索引器
get { return base[index]; } set { base[index] = value.Trim(); }继承List<string>。索引器不可覆盖。
【问题讨论】:
-
您为什么将
strList传递为ref?List<string>已经是一个引用类型。请记住,ref指的是 变量,而不是 值。 -
Eric Lippert:我知道我不必这样做;这更像是在提醒自己它是可变的,而字符串不是。
-
这是一种非常糟糕的编程习惯。仅在需要修改变量时传递
ref。