Здравствуйте, Аноним, Вы писали:
А>Забавно все это )
А>int? value = new int?(100); А>Type type = ((object)value).GetType(); // Int32 А>bool isGeneric = type.IsGenericType; // FALSE
When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable object itself.
так что результат вполне ожидаем.
Re: Как по Type определить Nullable и underlying type
Type someType;
if (someType.IsGenericType)
{
// Возможно Nullable<T>
Type srcGenericType = someType.GetGenericTypeDefinition();
// Реально Nullable<T>
Type nullableGenericType = typeof(int?).GetGenericTypeDefinition();
if (srcGenericType == nullableGenericType)
{
// baseType - Исходный не nullable тип
Type baseType = someType.GetGenericArguments()[0];
// ...
}
}
А>Как можно по someType определить что это Nullable тип, а также нижележащий тип — т.е. Enum. Спасибо!
Re[3]: Как по Type определить Nullable и underlying type
От:
Аноним
Дата:
13.12.06 08:22
Оценка:
Здравствуйте, desco, Вы писали:
D>Здравствуйте, Аноним, Вы писали:
А>>Забавно все это )
А>>int? value = new int?(100); А>>Type type = ((object)value).GetType(); // Int32 А>>bool isGeneric = type.IsGenericType; // FALSE
D>Nullable Generic Structure
D>
D>Boxing and Unboxing
D>When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable object itself.
D>так что результат вполне ожидаем.
упс это я лишнее поставил, экспериментировал. Без боксинга будет тот же результат.
Re[4]: Как по Type определить Nullable и underlying type
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
int? s = null;
ShowType(s);
}
public static void ShowType<T>(T obj)
{
Type mbNullAble = typeof(T);
if (mbNullAble.IsGenericType)
{
if (mbNullAble.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type type = Nullable.GetUnderlyingType(typeof(T));
Console.WriteLine(type.Name);
}
}
}
}
Re[2]: Как по Type определить Nullable и underlying type
Здравствуйте, <Аноним>, Вы писали:
А>Забавно все это )
int? value = new int?(100);
Type type = ((object)value).GetType(); // Int32bool isGeneric = type.IsGenericType; // FALSE
Все правильно. Ты вычисляешь реальный тип, а не задекларированный. И естественно, у константы 100 реальный тип — стандартный int. Это то же самое, как если бы ты написал:
object a = 100;
bool isGeneric = a.GetType().IsGenericType; // FALSE
1.2.0 alpha rev. 655
Уйдемте отсюда, Румата! У вас слишком богатые погреба.
Re[2]: Как по Type определить Nullable и underlying type