枚举的 c# 替代方案以获得智能感知优势

标签 c#

我有一个基类

abstract public class ComponentBase
{
    public List<string> Actions { get; set; }

    protected abstract void RegisterActions();
}

和它的 child

public class VideoBase : ComponentBase
{
    protected override void RegisterActions()
    {
        base.Actions.Add("Start video");
        base.Actions.Add("Pause video");
        base.Actions.Add("Rewind video");
    }
}

但为了让事情更简单,我还创建了枚举类型

public enum Actions
{
    START_VIDEO,
    PAUSE_VIDEO,
    REWIND_VIDEO,
}

我想要的是强制 ComponentBase 的每个 child 都有自己的枚举 Actions,但这似乎并不容易做到。或者,我虽然将操作列表更改为 Dictionary<string, string>但它并没有给我智能感知优势。我希望此类的用户能够轻松获得智能感知中的操作“列表”,而不是检查他们必须输入的字符串值,有什么建议吗?

最佳答案

在基类中使用泛型怎么样?

abstract public class ComponentBase<T> where T : struct
{
    //Example property.
    public T Action { get; set; }
}

As InBetween mentioned, in C# 7.3 you can add an additional constraint to force the generic type to be an enum:

abstract public class ComponentBase<T> where T : struct, System.Enum

这样你就可以指定在你的子类中继承 ComponentBase 时使用哪个枚举:

public class VideoBase : ComponentBase<VideoActions>
{
    ...your code...
}

public enum VideoActions
{
    START_VIDEO,
    PAUSE_VIDEO,
    REWIND_VIDEO
}
VideoBase video = new VideoBase();

//video.Action will now be of type VideoActions.
video.Action = VideoActions.START_VIDEO;

关于枚举的 c# 替代方案以获得智能感知优势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54006586/

相关文章:

c# - 如何计算 a^x=b 处的 x?

c# - Linq 是否消除了对 Hibernate 的需求?

c# - 如何将文本 block 与属性绑定(bind)

c# - 如何从类库中读取 "System.ServiceModel"配置节组?

c# - 使用 Azure AD v2.0 进行保护时,在 [Authorize] 修饰的 Web API 方法上收到 404

c# - 使用 C# 自定义配置

c# - 离开 While 循环?

c# - 静态变量以某种方式维护状态?

c# - 如何更新由 "code first from database"生成的数据库?

c# - 我可以引用当前 Select 对象中的属性吗?