代码之家  ›  专栏  ›  技术社区  ›  jac

用属性扩展String类?

  •  2
  • jac  · 技术社区  · 16 年前

    4 回复  |  直到 16 年前
        1
  •  7
  •   Konrad Rudolph    16 年前

    不,您不能使用属性扩展类。另外, String sealed string 在你自己的课堂上。

        2
  •  2
  •   Marc Gravell    16 年前

    听起来你应该创建自己的类:

    class Company {
        public string Name {get;set;}
        public override string ToString() {return Name;}
        // etc
    }
    

    现在绑定到一组 Company ToString 覆盖将确保 Name 默认情况下显示,您可以添加所需的任何其他内容。对于更复杂的场景,您可以使用(例如) DisplayMember ValueMember (指组合框)指向不同的属性(而不是默认属性 方法 ).

        3
  •  1
  •   Randolpho    16 年前

    您应该使用组合框而不是文本框。创建一个包含公司名称和id的自定义类型,确保它覆盖ToString以返回公司名称。将这些自定义类型添加到组合框中,而不是直接的字符串,并使用ListItems的AutoCompleteSource。

        4
  •  0
  •   jac    16 年前

    我使用了Konrad的答案,为了完整起见,我在这里发布了我的解决方案。我需要向用户显示一个自动完成的公司名称列表,但由于他们可能有多个同名公司,我需要Guid id在数据库中找到他们的选择。因此,我编写了自己的类,继承了AutoCompleteStringCollection。

        public class AutoCompleteStringWithIdCollection : AutoCompleteStringCollection
    {
        private List<Guid> _idList = new List<Guid>();
    
    
        /*-- Properties --*/
    
        public Guid this[int index]
        {
            get
            {
                return _idList[index];
            }
        }
    
        public Guid this[string value]
        {
            get
            {
                int index = base.IndexOf(value);
                return _idList[index];
            }
        }
    
        /*-- Methods --*/
    
        public int Add(string value, Guid id)
        {
            int index = base.Add(value);
            _idList.Insert(index, id);
            return index;
        }
    
        public new void Remove(string value)
        {
            int index = base.IndexOf(value);
            if (index > -1)
            {
                base.RemoveAt(index);
                _idList.RemoveAt(index);
            }
        }
    
        public new void RemoveAt(int index)
        {
            base.RemoveAt(index);
            _idList.RemoveAt(index);
        }
    
        public new void Clear()
        {
            base.Clear();
            _idList.Clear();
        }
    
    }