简体   繁体   English

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

[英]How to make a generic method allow returning null and accept enum?

How to make the following extension works? 如何进行以下扩展工作? I'm binding the ComboBoxe to an enum and in this case it doesn't compile because it returns null . 我将ComboBoxe绑定到枚举,在这种情况下,它不会编译,因为它返回null

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

    return (T)control.SelectedValue;
}

Note: I want it te return null (instead of default(T)). 注意:我希望它返回null(而不是默认值(T))。 The question is that what's the where expression that I've got to use? 问题是,我必须使用的表达方式是什么?

Return a nullable instead of a plain T : 返回一个可空的而不是一个普通的T

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

    return (T)control.SelectedValue;
}

That's impossible. 这不可能。 Value types cannot be null. 值类型不能为null。 Your extension method returns an instance of T and if this T is an enum (value type), its value cannot be null. 您的扩展方法返回T的实例,如果此T是枚举(值类型),则其值不能为null。 So without changing your return type such method signature simply cannot exist. 因此,在不更改返回类型的情况下,此类方法签名根本不存在。 As far as constraining the generic parameter to be an enum, that's also impossible in C# but possible in MSIL. 至于将泛型参数约束为枚举,这在C#中也是不可能的,但在MSIL中是可能的。 Jon has blogged about it . 乔恩在博客上写过这篇文章

在这种情况下,最常见的方法是在枚举的所有其他成员中定义None ,在这种情况下,在您的逻辑中为None == null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM