gpt4 book ai didi

c# - C# 参数中的键值对

转载 作者:IT王子 更新时间:2023-10-29 04:10:03 25 4
gpt4 key购买 nike

我正在寻找一种方法来实现以下功能:

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

我敢肯定有匿名类型的东西会很容易,但我没有看到。

我能想到的唯一解决方案是有一个 params KeyValuePair<String, object>[] pairs参数,但最终类似于:

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

诚然,这更丑陋。

编辑:

为了澄清,我正在写一个 Message类在 2 个不同的系统之间传递。它包含一个 ushort指定消息类型,以及与消息关联的“数据”对象的字符串字典。我希望能够在构造函数中传递所有这些信息,所以我可以这样做:

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

或类似的语法。

最佳答案

如果语法对于其他方面不错的模式来说是错误的,请更改语法。怎么样:

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 } });

关于c# - C# 参数中的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1319708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com