简体   繁体   English

具有可转换参数的泛型函数

[英]Generic function with convertable parameters

I want to write a generic function, that receives a list as a parameter. 我想编写一个通用函数,该函数接收一个列表作为参数。 If the list is null it should return null. 如果列表为null,则应返回null。 If the list contains valid items, it should return the first item. 如果列表包含有效项,则应返回第一项。 The function should work with all primitive data types like int, short, float, double etc... 该函数应适用于所有原始数据类型,例如int,short,float,double等。

In my example I use int: 在我的示例中,我使用int:

var a = new List<int>();
a.Add(3);

Foo<int, int?>(a);
Foo<int, int?>(null);

private T Foo<G, T>(List<G> list)
{
    if(list != null && list.Count > 0)
    {
        return list[0];
    }
    else
    {
        return default(T);
    }
}

This unfortunately does not work, because I did not find a generic constraint, that proves the compiler, that int? 不幸的是,这不起作用,因为我没有找到通用的约束,即证明了编译器的int吗? can be converted to int and short? 可以转换为int和short吗? to short etc... I only want to call the function with the primitive data types and their nullable pendants and also string. 简而言之,等等...我只想用原始数据类型及其可为空的坠子和字符串来调用函数。

Any ideas about another solution? 关于其他解决方案有什么想法吗? :-) :-)

Edit: 编辑:

It should also work with string. 它也应该与字符串一起使用。 Otherwise Rene Vogts solution would work. 否则,Rene Vogts解决方案将起作用。

Simply change the return type of the method, you only need one generic parameter, restricted to be a (non-nullable) value type: 只需更改方法的返回类型,您只需要一个通用参数,就只能将其限制为(非空)值类型:

private T? Foo<T>(List<T> list) where T : struct
{
    return list?.Count > 0 ? (T?)list[0] : null;
}

I don't think it's possible to make a single method that also can handle reference types like string . 我认为不可能制作一个也可以处理诸如string类的引用类型的方法。 But for reference types you can always use LINQ''s FirstOrDefault() and the null-conditional operator: 但是对于引用类型,您始终可以使用LINQ的FirstOrDefault()和空条件运算符:

List<string> list...
var result = list?.FirstOrDefault();

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

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