[英]How can I create an empty object field?
我需要將類似流氓的游戲編碼為項目,但我有一個小問題。 有一段時間我需要在使用開關創建哪個對象之間進行選擇。 我想在交換機外面聲明一個“空”對象,然后交換機用值填充對象。 這就是我想要做的事情:
Console.WriteLine("What race would you like to be?")
int answer = Convert.ToInt32(Console.ReadLine());
Object heroRace; // This is where the problem comes in
switch(answer)
{
case 1: heroRace = new Orc(); break;
case 2: heroRace = new Elf(); break;
}
我希望heroRace
在交換范圍之外進行重用。 如果我可以創建類似的東西,它將大大簡化我的程序。
在訪問其成員之前,您需要將對象強制轉換為更具體的類型
Object o=new Orc();
((Orc)o).methodNameWithinOrc();
但這可能導致鑄造異常。
例如..
((Elf)o).methodNameWithinOrc();
會導致一個轉換異常,因為o
是Orc
而不是Elf
的對象。
在使用is
運算符進行轉換之前,最好檢查對象是否屬於特定類
if(o is Orc)
((Orc)o).methodNameWithinOrc();
除非重寫ToString
, GetHashCode
..方法,否則Object
本身GetHashCode
應該是這樣的
LivingThingBaseClass heroRace;
Orc
和Elf
應該是LivingThingBaseClass
子類
LivingThingBaseClass
可以包含諸如move
, speak
, kill
之類的方法。這些方法中的所有或部分將被Orc
和Elf
覆蓋
LivingThingBaseClass
可以是abstract
類,甚至是interface
具體取決於您的要求
一般方法是:
interface IRace //or a base class, as deemed appropriate
{
void DoSomething();
}
class Orc : IRace
{
public void DoSomething()
{
// do things that orcs do
}
}
class Elf : IRace
{
public void DoSomething()
{
// do things that elfs do
}
}
現在,heroRace將被聲明(在開關外):
IRace heroRace;
在交換機內你可以:
heroRace = new Orc(); //or new Elf();
然后...
heroRace.DoSomething();
class test1
{
int x=10;
public int getvalue() { return x; }
}
class test2
{
string y="test";
public string getstring() { return y;}
}
class Program
{
static object a;
static void Main(string[] args)
{
int n = 1;
int x;
string y;
if (n == 1)
a = new test1();
else
a = new test2();
if (a is test1){
x = ((test1)a).getvalue();
Console.WriteLine(x);
}
if (a is test2)
{
y = ((test2)a).getstring();
Console.WriteLine(y);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.