![](/img/trans.png)
[英]How to allow a generic type parameter for a C# method to accept a null argument?
[英]How to make a generic method allow returning null and accept enum?
如何進行以下擴展工作? 我將ComboBoxe綁定到枚舉,在這種情況下,它不會編譯,因為它返回null
。
public static T GetSelectedValue<T>(this ComboBox control)
{
if (control.SelectedValue == null)
return null;
return (T)control.SelectedValue;
}
注意:我希望它返回null(而不是默認值(T))。 問題是,我必須使用的表達方式是什么?
返回一個可空的而不是一個普通的T
:
public static T? GetSelectedValue<T>(this ComboBox control) where T : struct
{
if (control.SelectedValue == null)
return null;
return (T)control.SelectedValue;
}
這不可能。 值類型不能為null。 您的擴展方法返回T
的實例,如果此T是枚舉(值類型),則其值不能為null。 因此,在不更改返回類型的情況下,此類方法簽名根本不存在。 至於將泛型參數約束為枚舉,這在C#中也是不可能的,但在MSIL中是可能的。 喬恩在博客上寫過這篇文章 。
在這種情況下,最常見的方法是在枚舉的所有其他成員中定義None
,在這種情況下,在您的邏輯中為None
== null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.