I would like to know if there's a specific constraint for numerical types that allows casting to work in the following case:
class MyClass<T>
{
...
void MyMethod()
{
....
byte value = AnotherObject.GetValue()
Tvalue = (T)value;
....
}
...
}
I tried boxing and unboxing like:
Tval开发者_如何学JAVAue = (T)(object)value;
But this only works if T == byte
. Otherwise I get an InvalidCastException
.
T is always a number type (like short, float, and so on).
Yes, you can only unbox a value to the same type.
Have you tried using
Tvalue = (T) Convert.ChangeType(value, typeof(T));
? Here's a sample:
using System;
class Test
{
static void Main()
{
TestChange<int>();
TestChange<float>();
TestChange<decimal>();
}
static void TestChange<T>()
{
byte b = 10;
T t = (T) Convert.ChangeType(b, typeof(T));
Console.WriteLine("10 as a {0}: {1}", typeof(T), t);
}
}
There's no constraint here, although you could specify
where T : struct, IComparable<T>
as a first pass. That constraint has nothing to do with the conversion working though - it would just be to attempt to stop callers from using an inappropriate type.
精彩评论