我正在尝试创建一个场景或状态管理器,它为每个状态存储一个Dictionary,作为加载或更改程序状态的方式(例如,主菜单状态和游戏状态)。我有一堆基类State的派生类,它们的变量不包含在基类State中。我可以安全地将它们存储在这本词典中吗?我有任何数据丢失吗?如果这不起作用,有什么方法可以实现我的目标?
答案 0 :(得分:1)
这似乎是你可以轻松测试自己的东西。但只是为了它的乐趣,假设你有一个基类,如:
public class Base
{
public string Name
{
get;
set;
}
public override string ToString()
{
return Name;
}
}
派生类如:
public class Derived : Base
{
public string Description
{
get;
set;
}
public override string ToString()
{
return base.ToString() + " - " + Description;
}
}
然后你可以创建这样的设置:
Base baseObject = new Base{ Name = "Base"};
Derived derivedObject = new Derived { Name = "Derived", Description = "Description" };
Dictionary<int, Base> dictionary = new Dictionary<int, Base>();
dictionary.Add(1, baseObject);
dictionary.Add(2, derivedObject);
现在你可以运行一点测试,看看是否丢失了任何信息:
foreach (Base value in dictionary.Values)
{
Console.WriteLine(value.ToString());
}
正如您所看到的,不仅调用了正确的重写ToString()
,而且它仍然具有Description
属性的正确值。所以不,你不会失去&#34;任何东西。但只要它是base
类型,您就只能直接访问base
属性。
顺便说一下。您还可以检查,如果值is
某个派生类型:
foreach (Base value in dictionary.Values)
{
if (value is Derived)
{
Console.WriteLine("{0} is Derived", value.Name);
// trying to access value.Description at this point
// would cause a compiler error "Cannot resolve symbol".
}
else
{
Console.WriteLine("{0} is not Derived", value.Name);
}
}
使用as
并检查null,您可以安全地&#34; (例如,无例外地由直接铸造引起)获得&#34; full&#34;派生类型,您可以再次访问所有其他属性:
foreach (Base value in dictionary.Values)
{
Derived derived = value as Derived;
if (derived != null)
{
Console.WriteLine("{0} is Derived and has Description: {1}",
derived.Name, derived.Description);
// now that derived actually is of type Derived,
// accessing derived.Description is perfectly fine.
}
}