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

对于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)

    {

    }

}


qq_遁去的一_1
浏览 63回答 1
1回答

呼如林

在 C# 中,您定义的构造可以适合多种类型,因此不能将其推断为 Dictionary。下面,我使用 params 关键字接受您指定的元组类型的数组,然后从中创建字典以调用需要字典的方法。&nbsp; &nbsp; private static void Main(string[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Test(("a", (1, "b")));&nbsp; &nbsp; &nbsp; &nbsp; TestWrap(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ("a", (1, "b")),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ("b", (3, "c"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }&nbsp; &nbsp; private static void Test((string, (int, string)) data)&nbsp; &nbsp; {&nbsp; &nbsp; }&nbsp; &nbsp; private static void TestWrap(params (string, (int, string))[] data)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Test2(data.ToDictionary(v => v.Item1, v => v.Item2));&nbsp; &nbsp; }&nbsp; &nbsp; private static void Test2(Dictionary<string, (int, string)> data)&nbsp; &nbsp; {&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP