I run into a compiler error that I am not sure how to resolve it.
Basically, I have a few enum classes described below.
I created abstract classes myTool and myTools deriving from myTool. The compiler for some reason does not like the way I structured the constructor for MyTools and threw error
CS0030: Can not convert type int to type T.
Please advice me how to resolve this.
public enum TOOLS
{
HAMMER =1,
DRILL = 2,
SCREWDRIVER =3,
VACUUM=4
}
public enum EQUIPMENTS
{
MOWER=1,
TRIMMER=2,
SNOWBLOWER=3
}
public abstract class MyTool
{
protected T _myStuff
int quantity
double price
public MyTool(T t)
{
_myStuff =t;
}
... properties...
}
public abstract class MyTools<T>:myTool<T>
where T:System.Enum
{
protected MyTool<T>[] _myTools;
public MyTool<T> this[int i]=> this._myTools[i];
public MyTools(int count, T t):base(t)
{
_myTools = new MyTools<T>[count];
for (int i=0; i<count;i )
{
_myTools[i]=(T)(i 1);
}
}
}
CodePudding user response:
You can convert an int
into a generic type constrained as System.Enum
like this:
T enumValue = (T)Enum.ToObject(typeof(T), intValue);
or simply
T enumValue = (T)(object)intValue;
CodePudding user response:
You can use generic type converter
public static class TConverter
{
public static T ChangeType<T>(object value)
{
return (T)ChangeType(typeof(T), value);
}
public static object ChangeType(Type t, object value)
{
TypeConverter tc = TypeDescriptor.GetConverter(t);
return tc.ConvertFrom(value);
}
public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
{
TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
}
}
and usage:
TConverter.ChangeType<T>(intValue);
it is from here: https://stackoverflow.com/a/1833128/2286743