Criação anulável via reflexão com HasValue = false, dado um parâmetro do tipo `Type 'apenas
Dado um parâmetro de tipo que é umNullable<>
, como posso criar uma instância desse tipo que tenhaHasValue = false
?
Em outras palavras, complete este código:
//type is guaranteed to implement Nullable<>
public static object Create(Type type)
{
//Instantiate a Nullable<T> with reflection whose HasValue = false, and return it
}
Minha tentativa, que não funciona (lança umNullReferenceException
) como não há construtor padrão:
static void Main(string[] args)
{
Console.WriteLine(Create(typeof(Nullable<int>)));
Console.ReadLine();
}
//type is guaranteed to be implement from Nullable<>
public static object Create(Type type)
{
//Instantatie a Nullable<T> with reflection whose HasValue = false, and return it
return type.GetConstructor(new Type[0]).Invoke(new object[0]);
}