I've a C# Code Snippts, which has error as :
Can not convert System.ValueType to T
Please guide me to solve this
here is a code
public static T Add<T>(this Enum type, T value)
{
try
{
return (T) (ValueType) (Convert.ToInt32(type) | (int) (object) value);
}
catch (Exception ex)
{
throw new ArgumentException(string.Format("Could not append value from enumerated type '{0}'.", (object) typeof (T).Name), ex);
}
}
now how could i run this error?
You could use Convert.ChangeType
For example,
var result = (ValueType) (Convert.ToInt32(type) | (int) (object) value);
return (T)Convert.ChangeType(result,typeof(T));
The compiler has no idea that T
can be upcasted from ValueType
as it doesn't know that T
is a value type. You'd need to add the struct
constraint for that.
public static T Add<T>(this Enum type, T value) where T : struct
Now that intermediate cast to ValueType
is equivalent to a cast to object
and it compiles.
However , this cast will fail with an InvalidCastException
if T
is anything else than int
or int?
(and it can't even be int?
with a struct
constraint). That's because doing (T)(object)
on an int
first boxes the integer and then tries to unbox it. And a boxed int
can only be unboxed to an int
or int?
(it's true for any value type, you can only unbox a value type T
to a variable of type T
or T?
). So this code being generic is close to useless, as it works with only one type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.