Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

parameters - Key value pairs in C# Params

I'm looking for a way to have a function such as:

myFunction({"Key", value}, {"Key2", value});

I'm sure there's something with anonymous types that would be pretty easy, but I'm not seeing it.

The only solution I can think of is to have a params KeyValuePair<String, object>[] pairs parameter, but that ends up being something similar to:

myFunction(new KeyValuePair<String, object>("Key", value),
           new KeyValuePair<String, object>("Key2", value));

Which is, admittedly, much uglier.

EDIT:

To clarify, I'm writing a Message class to pass between 2 different systems. It contains a ushort specifying the the Message Type, and a dictionary of string to object for "Data" associated with the message. I'd like to be able to pass all this information in the constructor, so I am able to do this:

Agent.SendMessage(new Message(MessageTypes.SomethingHappened, "A", x, "B", y, "C", z));

or similar syntax.

question from:https://stackoverflow.com/questions/1319708/key-value-pairs-in-c-sharp-params

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When the syntax is bad for an otherwise decent pattern, change the syntax. How about:

public void MyFunction(params KeyValuePair<string, object>[] pairs)
{
    // ...
}

public static class Pairing
{
    public static KeyValuePair<string, object> Of(string key, object value)
    {
        return new KeyValuePair<string, object>(key, value);
    }
}

Usage:

MyFunction(Pairing.Of("Key1", 5), Pairing.Of("Key2", someObject));

Even more interesting would be to add an extension method to string to make it pairable:

public static KeyValuePair<string, object> PairedWith(this string key, object value)
{
    return new KeyValuePair<string, object>(key, value);
}

Usage:

MyFunction("Key1".PairedWith(5), "Key2".PairedWith(someObject));

Edit: You can also use the dictionary syntax without the generic brackets by deriving from Dictionary<,>:

public void MyFunction(MessageArgs args)
{
    // ...
}

public class MessageArgs : Dictionary<string, object>
{}

Usage:

MyFunction(new MessageArgs { { "Key1", 5 }, { "Key2", someObject } });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...