请考虑以下代码:
void Handler(object o, EventArgs e)
{
// I swear o is a string
string s = (string)o; // 1
//-OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3
}
Run Code Online (Sandbox Code Playgroud)
三种类型的铸造之间有什么区别(好吧,第三种不是铸造,但是你得到了意图).应该首选哪一个?
可能重复:
使用CLR中的'as'关键字进行转换
这两个演员之间究竟有什么区别?
SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;
Run Code Online (Sandbox Code Playgroud)
通常,它们都应该显式转换为指定的类型?
我正在制作这个游戏,但我遇到了结构问题.我创建了一个名为Structure的类,其他类如Traps,Shelter,Fireplace继承自此类.游戏中的图块有自己的类(Tile),并且在该图块上有结构列表.我可以成功地在列表中包含的tile上构建结构.当我尝试从Traps等类中访问函数时,问题就出现了.它不起作用.我只能使用基类Structure中的函数.
列表中的列表:
class Tile
{
public List<Structure> Structures = new List<Structure>();
}
Run Code Online (Sandbox Code Playgroud)
我如何建造陷阱或其他建筑物:
bool anyFireplace = Bundle.map.tile[Bundle.player.X, Bundle.player.Y].Structures.OfType<Shelter>().Any();
if (!anyFireplace)
{
woodlogsCost = 4;
if (Bundle.player.Woodlogs - woodlogsCost >= 0)
{
Bundle.map.tile[Bundle.player.X, Bundle.player.Y].Structures.Add(new Shelter(Bundle.player.X, Bundle.player.Y));
Bundle.player.Woodlogs -= woodlogsCost;
}
}
Run Code Online (Sandbox Code Playgroud)
当我绘制结构时(这是我的问题所在,请注意注释)
foreach (Structure s in Bundle.map.tile[x, y].Structures)
{
if (s is Fireplace)
{
//This is the function from base class Strucure
s.ColorBody(g, 10, x - minx, y - miny, 0, Brushes.Firebrick);
// The function that I wan´t to use but …Run Code Online (Sandbox Code Playgroud) 在C#中,差异是什么
var obj = (Array)Something
Run Code Online (Sandbox Code Playgroud)
VS
var obj = Something as Array
Run Code Online (Sandbox Code Playgroud)