C# 如何声明泛型类型要使用的枚举?

C# 如何声明泛型类型要使用的枚举?,c#,generics,C#,Generics,我想在父抽象类中声明如下内容: public abstract void RefreshDisplay<TView>(Enum value); 公共抽象空刷新显示(枚举值); 然后在子类中实现,如: public override void RefreshDisplay<RxViewModel>(RxViews view) public覆盖无效刷新显示(RxViews视图) 其中,RxViews是一个枚举,“查看”该枚举中的特定值 直到运行时,才知道它来

我想在父抽象类中声明如下内容:

  public abstract void RefreshDisplay<TView>(Enum value);
公共抽象空刷新显示(枚举值);
然后在子类中实现,如:

   public override void RefreshDisplay<RxViewModel>(RxViews view)
public覆盖无效刷新显示(RxViews视图)
其中,RxViews是一个枚举,“查看”该枚举中的特定值

直到运行时,才知道它来自的实际视图和枚举

这能做到吗?我感谢你的帮助

编辑:我可能问错了。TView不是枚举,而是从ViewModelBase继承的视图。(我看不出这是一个重复的问题吗?)谢谢


编辑:我猜这是在Net4.5中修复的。如何在net 4.0中解决此问题,您有什么想法吗?

在.net 4.0中,对于带有
Enum
的泛型,您需要使用的约束类型如下-注意,您需要更改类声明以使其正常工作:

public abstract class BaseClass<TView, TEnum> 
    where TView: ViewModelBase
    where TEnum : struct,  IComparable, IFormattable, IConvertible
{

    public abstract void RefreshDisplay<TView, TEnum>(TEnum value);
}
类型检查是必要的,因为不能100%确定它是
Enum
(因为
Enum
实现了所有这些方面,这就是使用它们的原因)

您可能需要考虑更确切地说,使方法<代码>虚拟< /代码>,并包含在基本方法实现中。


请注意,此代码是根据此处提供的答案改编的:

您可以使用自定义类而不是枚举。基类可以定义为视图,您可以为每个TView继承它,并为每个值提供静态实例

public abstract class A
{
    public abstract void RefreshDisplay<TView>(Views<TView> value);
}

public abstract class Views<TView>
{
    internal Views() {} //Used to disallow inheriting from outside, not mandatory...

    //You can add other methods/properties to allow processing in RefreshDisplay method
}

public sealed class RxViews : Views<TView>
{
    private RxViews() {}

    private static readonly RxViews myFirstRxView = new RxViews();
    public static RxViews MyFirstRxView { get { return myFirstRxView; } }
}
公共抽象类A
{
公共摘要显示(视图值);
}
公共抽象类视图
{
内部视图(){}//用于禁止从外部继承,不是强制性的。。。
//您可以添加其他方法/属性以允许在RefreshDisplay方法中进行处理
}
公共密封类RxViews:视图
{
专用RxViews(){}
私有静态只读RxViews myFirstRxView=new RxViews();
公共静态RxViews MyFirstRxView{get{return MyFirstRxView;}}
}

重复为什么不使用两种通用类型,一种用于viewModel,另一种用于Enum,如下所示:public abstract void RefreshDisplay(TEnum值),其中TEnum:Enum;您可以使用自定义类而不是枚举。基类可以定义为视图,您可以为每个TView继承它,并为每个值提供静态实例。不要过于沉迷于类型安全;这可能是一个很好的心理练习,让一切都适合,但有时向上投射和断言更具可读性和实用性,类型理论本身也有一些松散的边缘。也考虑使用java样式的枚举:他如何指定重写方法中的泛型类?没有子类?他的类将变成<代码>类VIEW模型基础< /C>。
public abstract class A
{
    public abstract void RefreshDisplay<TView>(Views<TView> value);
}

public abstract class Views<TView>
{
    internal Views() {} //Used to disallow inheriting from outside, not mandatory...

    //You can add other methods/properties to allow processing in RefreshDisplay method
}

public sealed class RxViews : Views<TView>
{
    private RxViews() {}

    private static readonly RxViews myFirstRxView = new RxViews();
    public static RxViews MyFirstRxView { get { return myFirstRxView; } }
}