簡體   English   中英

僅給定類型為Type的參數,通過HasValue = false的反射可空創建

[英]Nullable create via reflection with HasValue = false, given a parameter of type `Type` only

給定類型參數為Nullable<> ,如何創建具有HasValue = false的該類型的實例?

換句話說,完成以下代碼:

//type is guaranteed to implement Nullable<>
public static object Create(Type type)
{
    //Instantiate a Nullable<T> with reflection whose HasValue = false, and return it
}

我的嘗試不起作用(它拋出NullReferenceException ),因為沒有默認的構造函數:

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]);
}

給定類型參數為Nullable<> ,如何創建具有HasValue = false的該類型的實例?

如果要使用帶有object簽名的方法,則只需返回null

//type is guaranteed to be implement from Nullable<>
public static object Create(Type type)
{
    return null;
}

這將始終是HasValue為null的任何可空類型值的框式表示形式。 換句話說,該方法是沒有意義的……您最好只使用null文字:

var i = (int?) null;

當然,如果不能保證type是可為空的值類型,則可能需要對代碼進行條件化……但重要的是要了解,不存在諸如Nullable<T>值的對象表示之類的東西。 即使對於非空值,裝箱的表示形式也是非空類型的裝箱的表示形式:

int? x = 5;
object y = x; // Boxing
Console.WriteLine(y.GetType()); // System.Int32; nullability has vanished

高度危險 (建議不要將其用於非測試目的)是使用SharpUtils的方法UnsafeTools.Box<T>(T? nullable) 它繞過可為空的類型的常規裝箱,該裝箱將其值裝箱或返回null,而是創建一個Nullable<T>的實際實例。 請注意,使用這樣的實例可能會遇到很多問題。

public static object Create<T>() where T : struct //T must be a normal struct, not nullable
{
    return UnsafeTools.Box(default(T?));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM