简体   繁体   中英

No Non Generic KeyValuePair class

I often use Tuple.Create on the Tuple class. Now I'm creating a KeyValuePair with:

new KeyValuePair<string, MyAnnoyingButNecessarilyVerboseClass>(myString, myObj)

I didn't want to include the type arguments in this case because they obfuscate the code a bit IMO. I've added the following to mimic Tuple.Create for KeyValuePairs .

public static class KVP
{
    public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value)
    {
        return new KeyValuePair<TKey, TValue>(key, value);
    }
}

So I can write

KVP.Create(myString, myObj)

without having to include type arguments explicitly because they are inferred from the other arguments. This works nicely, and I don't see any downsides. So I have a few very related questions.

  1. Why did C# not include a non generic System.KeyValuePair class with a static create method? ("They didn't because they didn't want to invest the effort for a feature that provides little value" is a completely acceptable and understandable answer)
  2. Am I missing a function that does something similiar?
  3. Are there downsides to creating a KeyValuePair class that I'm missing?
  4. Is there a more terse way to create a generic KeyValuePair (besides shortening the class and function name obviously :))?

Why did C# not include a non generic System.KeyValuePair class with a static create method? ("They didn't because they didn't want to invest the effort for a feature that provides little value" is a completely acceptable and understandable answer)

Question isn't a good fit for SO, doubtful it actually has an answer.

Am I missing a function that does something similiar?

No, as of .net 4.5 there isn't one in the framework.

Are there downsides to creating a KeyValuePair class that I'm missing?

No, I've created one myself.

Is there a more terse way to create a generic KeyValuePair ?

No, that's pretty much as terse as you could do it in C#

I think that KeyValuePair only exists at all because it predates Tuple by several versions of C#. With Tuple they just figured out a better way to do things.

a non generic equivalent for

KeyValuePair<TKey, TValue>

is

System.Collections.DictionaryEntry 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM