0

我正在对 a 进行重复工作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 不会类似地隐式转换。
  • List<string>用 indexer继承get { return base[index]; } set { base[index] = value.Trim(); }。索引器不可覆盖。
4

2 回答 2

13

有没有一种好方法(最好是直接替换),这样每次我写到时strList,里面的每个字符串都会自动修剪?

你不想要 的行为List<T>,所以不要使用List<T>. 相反,让你的方法接受IList<T>并提供一个实现你想要的接口。

实现可能只是一个包含 private 的包装类List<T>

另请参阅此相关问题:

如何在 C# 中覆盖 List<T> 的 Add 方法?

于 2013-07-05T16:51:18.840 回答
0

你可以使用

System.Collections.ObjectModel.ObservableCollection

而不是你的清单

并执行以下操作:

    ObservableCollection<string> myCollection = new ObservableCollection<string>();

    void Init()
    {
        myCollection.CollectionChanged +=myCollection_CollectionChanged;
    }

    void myCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        myCollection.CollectionChanged -= myCollection_CollectionChanged;
        //could be a delete / clear / remove at operation
        if (e.NewItems != null)
        {
            for (int i = 0; i < e.NewItems.Count; i++)
            {
                string str = (string)e.NewItems[i];
                //the added value could be null
                if (str != null)
                {
                    string trimmed = str.Trim();                        
                    if (!trimmed.Equals(str))
                    {
                        myCollection[e.NewStartingIndex + i] = str.Trim();
                    }
                }
            }
        }
        myCollection.CollectionChanged += myCollection_CollectionChanged;
    }

之后,每次修改 ObservableCollection 时,都会自动修剪添加的项目。

于 2013-07-05T16:54:19.903 回答