为了账号安全,请及时绑定邮箱和手机立即绑定

在没有完整类型声明的情况下创建字典作为参数的更短方法

在没有完整类型声明的情况下创建字典作为参数的更短方法

C#
qq_遁去的一_1 2022-11-21 16:11:51
对于Test2()下面的调用,有没有办法让它更短以省略显式输入?class Program{    static void Main(string[] args)    {        Test(("a", (1, "b")));        Test2(new Dictionary<string, (int, string)>()                { {"a", (1, "b") } });    }    static void Test((string, (int, string)) data)    {    }    static void Test2(Dictionary<string, (int, string)> data)    {    }}
查看完整描述

1 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

在 C# 中,您定义的构造可以适合多种类型,因此不能将其推断为 Dictionary。


下面,我使用 params 关键字接受您指定的元组类型的数组,然后从中创建字典以调用需要字典的方法。


    private static void Main(string[] args)

    {

        Test(("a", (1, "b")));

        TestWrap(

            ("a", (1, "b")), 

            ("b", (3, "c"))

            );

    }


    private static void Test((string, (int, string)) data)

    {

    }


    private static void TestWrap(params (string, (int, string))[] data)

    {

        Test2(data.ToDictionary(v => v.Item1, v => v.Item2));

    }


    private static void Test2(Dictionary<string, (int, string)> data)

    {

    }


查看完整回答
反对 回复 2022-11-21
  • 1 回答
  • 0 关注
  • 48 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信