How do I declare an Enum to be used as a generic type?

I would like to declare in the parent abstract class something like strings:

  public abstract void RefreshDisplay<TView>(Enum value);

      

which will then be implemented in the child class like:

   public override void RefreshDisplay<RxViewModel>(RxViews view)

      

Where RxViews is an enumeration and "view" of a specific value from that enumeration.

The actual view and the Enum it came from will not be known until runtime.

Can this be done? I appreciate the help.

Edit: I may have asked this incorrectly. TView is not an enumeration, but a view that inherits from ViewModelBase. (I can't see where this duplicate question is?) Thanks.

Edit: I assume this has been fixed in net 4.5. Any ideas how to get around this in net 4.0?

+3


source to share


2 answers


The type of constraint that you must use for generics Enum

in .NET 4.0 is as follows, note that you will need to change the class declaration to work properly:

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

    public abstract void RefreshDisplay<TView, TEnum>(TEnum value);
}

      

You should also do something similar to the following line in your method implementation:

if (!typeof(TEnum).IsEnum) { throw new ArgumentException("TEnum must be an enumerated type"); }

      



Type checking is necessary because it is not 100% sure what it is Enum

(tho ' Enum

implements all the aspects that make them used).

You might want to consider the method rather than virtual

include it in the base method implementation.

Note that this code is adapted from the answer given here: Create a generic method that constrains T to Enum

+11


source


You can use your own class instead of enumeration. The base class can be defined as Views, you inherit from each TView and provide static instances for each value.



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; } }
}

      

0


source







All Articles