如何使泛型方法允许返回null并接受枚举?

Fre*_*Boy 6 c# generics null enums

如何进行以下扩展工作?我将ComboBoxe绑定到枚举,在这种情况下,它不会编译,因为它返回null.

public static T GetSelectedValue<T>(this ComboBox control)
{
    if (control.SelectedValue == null)
        return null;

    return (T)control.SelectedValue;
}
Run Code Online (Sandbox Code Playgroud)

注意:我希望它返回null(而不是默认值(T)).问题是,我必须使用的表达方式是什么?

Kon*_*lph 6

返回一个可空的而不是一个普通的T:

public static T? GetSelectedValue<T>(this ComboBox control) where T : struct
{
    if (control.SelectedValue == null)
        return null;

    return (T)control.SelectedValue;
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 5

这不可能.值类型不能为null.您的扩展方法返回一个实例,T如果此T是枚举(值类型),则其值不能为null.因此,在不更改返回类型的情况下,此类方法签名根本不存在.至于将泛型参数约束为枚举,这在C#中也是不可能的,但在MSIL中是可能的.乔恩在博客上写过这篇文章.