C#参数中的键值对 [英] 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.
我唯一想到的解决方案是有一个params KeyValuePair<String, object>[] pairs
参数,但最终类似于:
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));
诚然,这要丑陋得多.
为澄清起见,我正在编写一个Message
类以在2个不同的系统之间传递.它包含指定消息类型的ushort
,以及与消息关联的数据"对象的字符串字典.我希望能够在构造函数中传递所有这些信息,所以我可以做到这一点:
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));
或类似语法.
推荐答案
如果语法对其他不错的模式不利,请更改语法.怎么样:
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);
}
}
用法:
MyFunction(Pairing.Of("Key1", 5), Pairing.Of("Key2", someObject));
更有趣的是向string
添加扩展方法以使其可配对:
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);
}
用法:
MyFunction("Key1".PairedWith(5), "Key2".PairedWith(someObject));
编辑:您还可以通过引用Dictionary<,>
来使用不带通用括号的字典语法:
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>
{}
用法:
MyFunction(new MessageArgs { { "Key1", 5 }, { "Key2", someObject } });
这篇关于C#参数中的键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!