如何从C#中的通用方法返回NULL?

我有一个使用此(虚拟)代码的通用方法(是的,我知道IList具有谓词,但是我的代码未使用IList但使用了其他集合,无论如何这与问题无关...)

static T FindThing<T>(IList collection, int id) where T : IThing, new()
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return thing;
    }
    return null;  // ERROR: Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead.
}

这给了我一个构建错误

“无法将null转换为类型参数'T',因为它可能是值类型。请考虑改用'default(T)'。”

我可以避免这个错误吗?


#1楼

  1. 如果您有对象,则需要打字

     return (T)(object)(employee); 
  2. 如果需要返回null。

     return default(T); 

#2楼

这是Nullable Enum返回值的工作示例:

public static TEnum? ParseOptional<TEnum>(this string value) where TEnum : struct
{
    return value == null ? (TEnum?)null : (TEnum) Enum.Parse(typeof(TEnum), value);
}

#3楼

return default(T);

#4楼

根据错误的建议...以及用户default(T)new T

您必须在代码中添加一个比较,以确保沿着该路线进行匹配是有效的。

否则,可能考虑将输出参数用于“找到匹配项”。


#5楼

两种选择:

  • 返回default(T)其意味着你将返回null如果T是引用类型(或空值类型), 0int'\\0'char等。( 默认值表(C#参考)
  • 使用where T : class约束将where T : class限制为引用类型,然后正常返回null

#6楼

您的另一个选择是将其添加到声明的末尾:

    where T : class
    where T: IList

这样,它将允许您返回null。


#7楼

您可以调整约束:

where T : class

然后允许返回null。


#8楼

将类约束作为第一个约束添加到泛型类型。

static T FindThing<T>(IList collection, int id) where T : class, IThing, new()

#9楼

以下是您可以使用的两个选项

return default(T);

要么

where T : class, IThing
 return null;

#10楼

上述2个答案的另一种选择。 如果将返回类型更改为object ,则可以返回null ,同时强制转换非null返回值。

static object FindThing<T>(IList collection, int id)
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return (T) thing;
    }
    return null;  // allowed now
}

#11楼

TheSoftwareJedi的解决方案,

您也可以使用几个值和可为空的类型将其归档:

static T? FindThing<T>(IList collection, int id) where T : struct, IThing
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return thing;
    }
    return null;
}
发布了0 篇原创文章 · 获赞 2 · 访问量 4028

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/103970971
今日推荐