更改字典成员的类型

在课堂上,我声明了 Dictionary 的泛型(基类)类型:

private Dictionary<string, Animal> dict = new Dictionary<string, Animal>();

后来我添加了个体动物(它们都来自动物)

dict["cat"] = (Cat) new Cat();
dict["dog"] = (Dog) new Dog();

Cat 具有名为 的属性tail。但是,当我稍后在 IDE 中尝试访问该成员时,dict["cat"].tail未定义。因为该成员解析为Animalstill,而不是Cattype。

如何强制/更改dict["cat"].tailIDE 中可用的字典成员类型?

ps 我是否每次都将类型添加到该变量中? ((Cat)dict["cat"]...


30秒到达战场
浏览 147回答 3
3回答

慕桂英546537

要使用你的猫的属性尾巴,你必须先施放你的猫((Cat)&nbsp;dict['cat']).tail因为当你把你的猫放在你的字典中时,如果你试图通过你的字典访问它,它会被认为是一个动物,而你的 Animal 类没有这个属性,而 Cat 类有PS:如果你只有猫和狗,也许Animal可以有这个属性?

森林海

您必须使用as运算符来转换字典条目,这在dict["cat"]错误地包含Dog. (Cat)dict["cat"]在这种情况下使用会抛出异常。if (dict.ContainsKey("cat")){&nbsp; &nbsp; Cat dictCat = dict["cat"] as Cat;&nbsp; &nbsp; if (dictCat != null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // use dictCat&nbsp; &nbsp; }}字典只会将值视为Animals,因此每次要使用派生类的成员时确实都必须进行强制转换。正如 CodeNotFound 在评论中提到的,模式匹配(在 C# 7 中引入)是另一种可用的选项。if (dict.ContainsKey("cat") && dict["cat"] is Cat cat){&nbsp; &nbsp; // Dealing with cat :)&nbsp;}

宝慕林4294392

首先,你不必做dict["cat"] = (Cat) new Cat();dict["dog"] = (Dog) new Dog();由于Cat和Dog派生自Animal,您可以直接分配它们dict["cat"] = new Cat();dict["dog"] = new Dog();现在,要访问单个属性,请使用(dict["cat"] as Cat)?.tail其中已经包括null通过?.运营商的支票
打开App,查看更多内容
随时随地看视频慕课网APP