我正在寻找一种方法来实现如下功能:
myFunction({"Key", value}, {"Key2", value});我相信有一些匿名类型的东西是非常容易的,但我没有看到它。
我能想到的唯一解决方案是有一个params KeyValuePair<String, object>[] pairs参数,但最终结果类似于:
myFunction(new KeyValuePair<String, object>("Key", value),
new KeyValuePair<String, object>("Key2", value));无可否认,这要丑陋得多。
编辑:
为了清楚起见,我正在编写一个在两个不同系统之间传递的Message类。它包含一个指定消息类型的ushort,以及一个用于与消息关联的“数据”对象的字符串字典。我希望能够在构造函数中传递所有这些信息,所以我可以这样做:
Agent.SendMessage(new Message(MessageTypes.SomethingHappened, "A", x, "B", y, "C", z));或类似的语法。
发布于 2009-08-23 22:39:33
当语法对于其他合适的模式来说不是很好时,改变语法。这样如何:
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添加一个扩展方法,使其可配对:
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<,>派生来使用不带通用括号的字典语法
public void MyFunction(MessageArgs args)
{
// ...
}
public class MessageArgs : Dictionary<string, object>
{}用法:
MyFunction(new MessageArgs { { "Key1", 5 }, { "Key2", someObject } });发布于 2017-12-08 21:51:00
从C# 7.0开始,您可以使用值元组。C# 7.0不仅引入了一种新类型,而且为元组类型和元组值引入了简化的语法。元组类型被简单地写成一个用大括号括起来的类型列表:
(string, int, double)相应的元素被命名为Item1、Item2、Item2。您还可以指定可选的别名。这些别名只是语法糖( C#编译器的一个技巧);元组仍然基于不变的(但通用的) System.ValueTuple struct。
(string name, int count, double magnitude)元组值具有类似的语法,不同之处在于指定表达式而不是类型
("test", 7, x + 5.91)或使用别名
(name: "test", count: 7, magnitude: x + 5.91)params数组示例:
public static void MyFunction(params (string Key, object Value)[] pairs)
{
foreach (var pair in pairs) {
Console.WriteLine($"{pair.Key} = {pair.Value}");
}
}也可以像这样解构一个元组
var (key, value) = pair;
Console.WriteLine($"{key} = {value}");这将在两个独立的变量key和value中提取元组中的项。
现在,您可以轻松地使用不同数量的参数调用MyFunction:
MyFunction(("a", 1), ("b", 2), ("c", 3));
它允许我们做像这样的事情
DrawLine((0, 0), (10, 0), (10, 10), (0, 10), (0, 0));发布于 2009-08-24 00:45:30
有趣的是,我刚刚(几分钟前)创建了一个方法,使用匿名类型和反射来实现这一点:
MyMethod(new { Key1 = "value1", Key2 = "value2" });
public void MyMethod(object keyValuePairs)
{
var dic = DictionaryFromAnonymousObject(keyValuePairs);
// Do something with the dictionary
}
public static IDictionary<string, string> DictionaryFromAnonymousObject(object o)
{
IDictionary<string, string> dic = new Dictionary<string, string>();
var properties = o.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
dic.Add(prop.Name, prop.GetValue(o, null) as string);
}
return dic;
}https://stackoverflow.com/questions/1319708
复制相似问题