I have a function to return me the class instance. Here it is:
public class Warrior{
private Type GetSpec()
{
if ((WarriorSpecs)charData.CharacterSpec == WarriorSpecs.Barbarian)
{
return new Barbarian(charData).GetType();
}
if ((WarriorSpecs)charData.CharacterSpec == WarriorSpecs.Guardian)
{
return new Guardian(charData).GetType();
}
if ((WarriorSpecs)charData.CharacterSpec == WarriorSpecs.Knight)
{
return new Knight(charData).GetType();
}
return this.GetType();
}
}
All those classes Barbarian
,Guardian
,Knight
are child classes of the class Warrior
.
My question is why I cannot do the following:
public void FunctionInWarriorClass(){
GetSpec.AnotherVoidInWarriorClass();
}
All I want is GetSpec
to return an instance of any of those classes which are child classes and then call a function declared in Warrior
class. Is that even possible?
答案 0 :(得分:5)
那是因为GetSpec()返回Type对象而不是Warrior子类。
尝试一下:
private Warrior GetSpec()
{
if ((WarriorSpecs)charData.CharacterSpec == WarriorSpecs.Barbarian)
{
return new Barbarian(charData);
}
if ((WarriorSpecs)charData.CharacterSpec == WarriorSpecs.Guardian)
{
return new Guardian(charData);
}
if ((WarriorSpecs)charData.CharacterSpec == WarriorSpecs.Knight)
{
return new Knight(charData);
}
return this;
}