我正在学习 C# 和 Unity。
问题 1:为什么将 foreach 与数组或列表一起使用,指定变量的类型和名称就足够了,但是对于字典 - 您需要使用 var 声明它(和子问题:我是 C# 新手,据我所知,变量通常是在没有 var 的情况下声明的)?
问题 2:为什么在使用字典时,可以不设置 foreach 循环变量的类型——它会自行确定,而在数组和列表的情况下——这是必要的吗?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestScript : MonoBehaviour {
//Array
string[] names = new string[]{"Name", "Surname"};
//List
List<string> animals = new List<string>(){"dog", "cat", "cow"};
//Dictionary
Dictionary<string,string> clothes = new Dictionary<string, string>();
void Start () {
clothes.Add("slot1", "hat");
clothes.Add("slot2", "t-shirt");
LoopTest();
}
void LoopTest(){
//foreach loop goes through names array
foreach (string name in names) {
print (name);
}
//foreach loop goes through animals list
foreach (string name in animals) {
print (name);
}
//foreach loop goes through clothes dictionary
foreach (var item in clothes) {
print (item.Key + " " + item.Value);
}
}
}
它只是语法的一个特征,还是这里有某种逻辑?非常感谢!
真的没有区别。问题是这个变量有什么类型。
您如何
List<string>
将变量类型设置为string
?而且很简单:你看到List<string>
接口实现了什么IEnumerable<string>
,也就是说变量的类型是string
。它以相同的方式
Dictionary<string, string>
实现接口IEnumerable<KeyValuePair<string, string>>
。这意味着一切都必须使用变量 type 进行编译KeyValuePair<string, string>
。在这两种情况下,您都可以显式设置类型,也可以不设置。