简体   繁体   English

用一个键声明多个值的字典

[英]Declare dictionary with one key multiple values

C# I am using a dictionary like: C#我正在使用像这样的字典:

var dict = new Dictionary<byte, Tuple<string, string>>();           
Tuple<string, string> t = new Tuple<string, string>(label, unit);

I want to declare it as a data member of the class. 我想将其声明为该类的数据成员。 but it says 但它说

The contextual keyword 'var' may only appear within a local variable declaration or in script code 上下文关键字“ var”只能出现在局部变量声明中或脚本代码中

How do I solve this? 我该如何解决?

The error message is pretty clear. 错误消息很清楚。 You cannot use var to declare class members, only for local variables. 您不能仅使用局部变量来使用var声明类成员。

For class members you need to use the explicit type: 对于类成员,您需要使用显式类型:

public class MyClass
{
    Dictionary<byte, Tuple<string, string>> dict = new Dictionary<byte, Tuple<string, string>>();

    // ...
}

in C# you cannot use var to declare class members: 在C#中,您不能使用var声明类成员:

here are technical issues with implementing this feature. 这是实现此功能的技术问题。 The common cases seem simple but the tougher cases (eg, fields referencing other fields in chains or cycles, expressions which contain anonymous types) are not. 常见情况看似简单,但较困难的情况(例如,在链或循环中引用其他字段的字段,包含匿名类型的表达式)却并非如此。

taken from the blog post Why no var on fields? 摘自博客文章为什么字段上没有var? and from this post . 和从这个职位

In such case, you need to declare explicit types: 在这种情况下,您需要声明显式类型:

Dictionary<byte, Tuple<string, string>> dict = new Dictionary<byte, Tuple<string, string>>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM