Why can't I cast a generic type to a value type
This may be a basic question but why can't I cast a generic type back to it's original type when passing a list of value types into a generic method ?
IList<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
Inverse<int>(list);
public void Inverse<T>(IList<T> list)
{
for (i = 0; i <= list.Count / 2; i++)
开发者_JAVA技巧 {
int a = list[i] as Int16; //=> does not work
int b = (int)list[i]; //=> does not work either
}
}
I'd expect it not to, you've completely missed the point of a generic method there as you're assuming the types in the IList are 'int'.
If you did:
T a = (T)list[i]
then it would work.
Well, since there is no constraint on T, the second error is to prevent something like
Inverse<Person>(new List<Person>());
as for the first error, as
only works for reference types and again since T has no constraint, the compiler cannot infer anything.
You're doing it wrong. Inverse accept any type of T, not just int. Replace the occurence of int with T
int b = Convert.ToInt32(list[i]);
instead of
int b = (int)list[i];
That is because the compiler doesn't know what type it is & hence throws compiler error on it. I am not sure, if it works in c# 4, with type inference.
EDIT: as
statement cannot work in your example because
The as operator is used to perform certain types of conversions between compatible reference types
reference: http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx
You cant use as Int16
because you are trying to cast an object reference, but Int16
(short) is a value type. But your design also misses the point of generics: You are expecting an integer but use a generic method, so T could really be anything.
精彩评论