为什么这一行代码(下面的上下文)
if (spellEnum == Spell.Fireball) return "Fire ball";产生错误:
‘拼写’是一个类型参数,在给定的上下文中无效。
public abstract class DataSet : ScriptableObject
{
public abstract string DisplayName<T>(T arg) where T : Enum;
}
public enum Spell { Fireball, Icestorm, MagicMissile };
public class SpellDataSet : DataSet
{
public override string DisplayName<Spell>(Spell spellEnum)
{
if (spellEnum == Spell.Fireball) return "Fire ball";
return "Other spell";
}
}
public class DataLibrary
{
void main()
{
SpellDataSet spellDataSet = new SpellDataSet();
strint test = spellDataSet.DisplayName(Spell.Fireball);
}
}我希望有一种通用的方法来访问有关各种类型(拼写、项目、字符)的数据,以及通过该类型各自的枚举(拼写)访问的特定类型的数据(Spell1、Spell2等),并且所有类型的通用方法(在抽象类中定义)都会产生对用户友好的名称(DisplayName)。
发布于 2021-02-15 09:03:48
我仍然不明白为什么原始代码会产生错误,但是我已经通过使抽象类泛化而不仅仅是DisplayName方法实现了我想要的结果。起作用的代码:
public abstract class DataSet<T> : ScriptableObject where T: Enum
{
public abstract string DisplayName(T arg);
}
public enum Spell { Fireball, Icestorm, MagicMissile };
public class SpellDataSet : DataSet<Spell>
{
public override string DisplayName(Spell spellEnum)
{
if (spellEnum == Spell.Fireball) return "Fire ball";
return "Other spell";
}
}
public class DataLibrary
{
void main()
{
SpellDataSet spellDataSet = new SpellDataSet();
string test = spellDataSet.DisplayName(Spell.Fireball);
}
}https://stackoverflow.com/questions/66204945
复制相似问题