Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在C#中创建一个使用字典(应用于所有数据类型)作为参数的方法吗? public void方法(字典dict) { foreach(dict中的var o) { 控制台写入线(o); } }_C#_.net - Fatal编程技术网

我可以在C#中创建一个使用字典(应用于所有数据类型)作为参数的方法吗? public void方法(字典dict) { foreach(dict中的var o) { 控制台写入线(o); } }

我可以在C#中创建一个使用字典(应用于所有数据类型)作为参数的方法吗? public void方法(字典dict) { foreach(dict中的var o) { 控制台写入线(o); } },c#,.net,C#,.net,然后当我们需要调用该方法时,我们可以在那里放置任何类型的字典。 e、 方法(新字典());方法(新字典()); 我们能做到吗?另外,我们可以为任何类型的数据类型输出字典吗?我推荐 这是你的案例的一个片段 public void Method(Dictionary<any datatype, any datatype> dict) { foreach (var o in dict) { Console.WriteLine(o); }

然后当我们需要调用该方法时,我们可以在那里放置任何类型的字典。 e、 方法(新字典());方法(新字典()); 我们能做到吗?另外,我们可以为任何类型的数据类型输出字典吗?

我推荐

这是你的案例的一个片段

public void Method(Dictionary<any datatype, any datatype> dict)  
{     
    foreach (var o in dict)
    {
        Console.WriteLine(o);
    } 
}
static void Main(字符串[]args)
{
//示例字典来自
//从https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8
//使用字符串键创建一个新的字符串字典。
//
字典openWith=
新字典();
//向字典中添加一些元素。没有
//重复的键,但某些值是重复的。
openWith.Add(“txt”、“notepad.exe”);
openWith.Add(“bmp”、“paint.exe”);
openWith.Add(“dib”、“paint.exe”);
openWith.Add(“rtf”、“wordpad.exe”);
打印(openWith);
}
静态无效打印(字典数据)
{
foreach(数据中的var o)
{
控制台写入线(o);
}
}

查找泛型。这实际上就是基线泛型。好吧,也许有点高级,因为只有这个函数是通用的。通常你们会为整个类做泛型,而不仅仅是一个函数。谢谢你们,我是一个非常非常初学者。再次感谢你的建议。
static void Main(string[] args)
{
    // Example dictionary from
    // from https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8
    // Create a new dictionary of strings, with string keys.
    //
    Dictionary<string, string> openWith =
        new Dictionary<string, string>();

    // Add some elements to the dictionary. There are no 
    // duplicate keys, but some of the values are duplicates.
    openWith.Add("txt", "notepad.exe");
    openWith.Add("bmp", "paint.exe");
    openWith.Add("dib", "paint.exe");
    openWith.Add("rtf", "wordpad.exe");

    Print(openWith);
}

static void Print<T, U>(Dictionary<T, U> data)
{
    foreach (var o in data)
    {
        Console.WriteLine(o);
    }
}