Re[4]: Как по Type определить Nullable и underlying type
От: desco США http://v2matveev.blogspot.com
Дата: 13.12.06 08:31
Оценка: 11 (1) +1
Здравствуйте, Аноним, Вы писали:

вызов GetType у value типов на стеке приведет к боксингу

            int a = 0;
            a.GetType();


      .entrypoint
      .maxstack 1
      .locals init (
            [0] int32 x)
      L_0000: nop 
      L_0001: ldc.i4.0 
      L_0002: stloc.0 
      L_0003: ldloc.0 
      L_0004: box int32
      L_0009: call instance [mscorlib]System.Type object::GetType()
      L_000e: pop 
      L_000f: ret
Re[2]: Как по Type определить Nullable и underlying type
От: desco США http://v2matveev.blogspot.com
Дата: 13.12.06 08:12
Оценка: 1 (1)
Здравствуйте, Аноним, Вы писали:

А>Забавно все это )


А>int? value = new int?(100);

А>Type type = ((object)value).GetType(); // Int32
А>bool isGeneric = type.IsGenericType; // FALSE

Nullable Generic Structure

Boxing and Unboxing

When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable object itself.


так что результат вполне ожидаем.
Как по Type определить Nullable и underlying type
От: Аноним  
Дата: 13.12.06 07:44
Оценка:
Здравствуйте! Есть такой код


enum SomeEnumType
{
  ...
}

class Foo
{
  SomeEnumType? val;
}

private static void Main()
{
   Foo foo = new Foo();
   Type someType = получаем тип свойства val;
   SomeMethod(someType);
}

public void SomeMethod(Type someType)
{
  
}



Как можно по someType определить что это Nullable тип, а также нижележащий тип — т.е. Enum. Спасибо!
Re: Как по Type определить Nullable и underlying type
От: desco США http://v2matveev.blogspot.com
Дата: 13.12.06 07:59
Оценка:
Здравствуйте, Аноним, Вы писали:

<skipped>

А>Как можно по someType определить что это Nullable тип, а также нижележащий тип — т.е. Enum. Спасибо!



        private static void Print<T>(T obj)
        {
            Type t = typeof (T);
            if (t.IsGenericType)
            {
                if (t.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    Console.WriteLine("Nullable");
                    Console.WriteLine(t.GetGenericArguments()[0].IsEnum);
                }
                else
                {
                    Console.WriteLine("Not nullable");
                }
            }
        }
Re: Как по Type определить Nullable и underlying type
От: Аноним  
Дата: 13.12.06 08:01
Оценка:
Забавно все это )

int? value = new int?(100);
Type type = ((object)value).GetType(); // Int32
bool isGeneric = type.IsGenericType; // FALSE
Re: Как по Type определить Nullable и underlying type
От: SVRC Украина  
Дата: 13.12.06 08:21
Оценка:
Здравствуйте, Аноним, Вы писали:

А>Здравствуйте! Есть такой код


А>

А>enum SomeEnumType
А>{
А>  ...
А>}

А>class Foo
А>{
А>  SomeEnumType? val;
А>}

А>private static void Main()
А>{
А>   Foo foo = new Foo();
А>   Type someType = получаем тип свойства val;
А>   SomeMethod(someType);
А>}

А>public void SomeMethod(Type someType)
А>{
  
А>}

А>



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: Как по Type определить Nullable и underlying type
От: ncoder  
Дата: 13.12.06 09:20
Оценка:
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
От: Sinclair Россия https://github.com/evilguest/
Дата: 13.12.06 14:50
Оценка:
Здравствуйте, <Аноним>, Вы писали:

А>Забавно все это )


int? value = new int?(100);
Type type = ((object)value).GetType(); // Int32
bool 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
От: alexanderfedin США http://alexander-fedin.pixels.com/
Дата: 14.12.06 05:04
Оценка:
Здравствуйте, desco, Вы писали:
А>>Как можно по someType определить что это Nullable тип, а также нижележащий тип — т.е. Enum. Спасибо!
D>
D>        private static void Print<T>(T obj)
D>        {
D>


Если тип известен на этапе компиляции, как это имеется в виду у Вас, то:
    private static bool IsNullable<T>(T obj, out Type underlyingType)
    {
        underlyingType = typeof(T);
        return false;
    }
    private static bool IsNullable<T>(Nullable<T> obj, out Type underlyingType)
    {
        underlyingType = typeof(T);
        return true;
    }
Respectfully,
Alexander Fedin.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.