문제

I have an IDictionary<TKey, TValue> where the TKey is a class. Can I add the ability to use the Indexer with a String value instead of a TKey?

public class MyClass {
  public string Name { get; set; }
}

....

//dict is a IDictionary<MyClass, object> 
dict.Add(new MyClass { Name = "Foo" });

Currently I'm using Linq to access the values by Name but I would prefer something like this:

//This call returns the variable I added above
object value = dict["Foo"];

Is this possible?

도움이 되었습니까?

해결책 2

This might be a good approach to your problem, if using the Name to define equality makes sense for MyClass generally, and not just in this particular dictionary:

public class MyClass
{
    public string Name { get; set; }
    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }
    public override bool Equals(object other)
    {
        return this.Name == ((MyClass)other).Name;
    }
}

Then your dictionary is simply indexed by MyClass objects. If you have an explicit string instead of a MyClass instance, you can get the dictionary's value like this:

dict[new MyClass { Name = "Foo" }]

You could also add a:

public static implicit operator MyClass(string s)
{
    return new MyClass { Name = s };
}

And index like:

dict["Foo"]

Again, only do this if it makes sense for MyClass generally, not just for use in this particular dictionary. If it's for this particular dictionary, try another solution.

다른 팁

You could create your own dictionary class based on your class.

public class MyClass
{
    public string Name { get; set; }

    // You may want to implement equality members on your class so that 
    // the dictionary treats the Name value as the key correctly.
}

public class MyClassDictionary<TValue> : Dictionary<MyClass, TValue>
{
    public TValue this[string val]
    {
        get
        {
            return base[Keys.First(x => x.Name == val)];
        }
    }
}

You can then use this as you wanted to.

MyClassDictionary<string> instance = new MyClassDictionary<string>();

instance.Add(new MyClass() { Name = "testkey" }, "test value");

Debug.WriteLine(instance["testkey"]);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top