我有一个基类
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/