首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么在以enum为类型的泛型方法中使用specifc enum无效?

为什么在以enum为类型的泛型方法中使用specifc enum无效?
EN

Stack Overflow用户
提问于 2021-02-15 08:43:13
回答 1查看 21关注 0票数 1

为什么这一行代码(下面的上下文)

代码语言:javascript
复制
if (spellEnum == Spell.Fireball) return "Fire ball";

产生错误:

‘拼写’是一个类型参数,在给定的上下文中无效。

代码语言:javascript
复制
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)。

EN

回答 1

Stack Overflow用户

发布于 2021-02-15 09:03:48

我仍然不明白为什么原始代码会产生错误,但是我已经通过使抽象类泛化而不仅仅是DisplayName方法实现了我想要的结果。起作用的代码:

代码语言:javascript
复制
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);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66204945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档