开发者

How to extract string representation of key object

I'm storing items in a strongly typed IDictionary<TKey, TValue> such that the value also represents the key:

public class MyObject
    {

        public string Name { get; private set; }
        public SectionId Section { get; private set; }

        public MyObject(SectionId section, string name)
        {
            Section = section;
            Name = name;
        }
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof(MyObject)) return false;
            return E开发者_JAVA百科quals((MyObject)obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return (Name.ToLower().GetHashCode() * 397) ^ Section.GetHashCode();
            }
        }

    }

In my presentation tier, I need to iterate through this Dictionary, adding each item to a ListBox control. I'm having a difficult time figuring out how to transform MyObject (which also acts as a key) into a string that the ListBox control can use as a value. Should I just make an explicit call to MyObject.GetHashCode() like this:

MyListBox.Add(new ListItem(myObject.Name, myObject.GetHashCode())


I would think of overriding the toString method and in here you will basically write code that will generate a meaningful string to be displayed in the ui

Hope I understood your question correctly.


Should I just make an explicit call to MyObject.GetHashCode()

No, GetHashCode() is:

  1. Not guaranteed to give you a unique value, and
  2. Going to be very difficult to reverse-engineer to produce a MyObject from.

Instead, each of your MyObjects should have some kind of unique identifier key. This can be an enum value or a number generated by an IDENTITY column in your database, or just a string that uniquely identifies each particular MyObject, and from which you can retrieve the MyObject from whatever collection or database you're using as a repository.

If there can only ever be a single MyObject with a given Name and Section, you could just combine the two: SectionId + ":" + Name. That way you can parse those two values out after the fact.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜