如何将泛型类型参数传递给lambda表达式? [英] How to pass Generic Type parameter to lambda expression?

查看:164
本文介绍了如何将泛型类型参数传递给lambda表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个lambda表达式,它接受一个int?(可为空的整数),
如果值存在或 DBNull.Value 会返回值否则.

I have a lambda expression which accepts, a int? (nullable integer),
which returns value if value exists or DBNull.Value otherwise.

Func<int?, object> getId = id => id.HasValue ? id.Value : (object)DBNull.Value;

这里的目标是,我想使该表达式稍微通用一些,以便我可以传递任何可空类型,例如DateTime?

The goal here is that, I want to make that expression slightly a bit more generic so that I can pass any nullable types like, DateTime?

所以这是我刚开始使用的非功能代码,但不确定在何处指定可空值的 type .

So here is a non-functional code I was starting off with, but not sure where to specify nullable's type.

int? imageId;
DateTime? actionDate;
Func<Nullable<T>, object> getValue = 
    id => id.HasValue ? id.Value : (object) DBNull.Value;
SaveImage(getValue(imageId), getValue(actionDate));

是否可以指定通用类型,还是应该创建一个命名函数?

Is it possible to specify generic type or should I create a named function to do so?

推荐答案

由于问题的目的是使用lambda表达式,因此这里提供了一种解决方案.通过使用弱类型而不是提议的强类型,它采取了不同的途径,但是仍然完成了相同的事情.

Since the purpose of the question is to use a lambda expression, here is a solution. It takes a different route by using weak typing instead of the proposed strong typing, but accomplishes the same thing nonetheless.

        // A lambda solution
        Func<object, object> fnGetValue =
            v =>
                ReferenceEquals(v, null)
                ? DBNull.Value
                : v;


        // Sample usage
        int? one = 1;
        int? two = null;
        object o1 = fnGetValue(one); // gets 1
        object o2 = fnGetValue(two); // gets DBNull

编辑:之所以可以使用这种松散类型,是因为lambda参数v的数据类型是结构本身,而不是Nullable类型包装器.显然,在调用lambda参数并且lambda参数显示结构值或null时,调用方使用的Nullable值已被解析或解包".在这一点上(或据我所知),Nullable包装器无处可见.可以通过在v的lambda中放置调试断点并检查其值来证明此行为. 这种行为的良好副作用是,lambda对于Nullable和Non-Nullable类型都同样有效-不受限制.

Edit: This loose typing works because the data type of the lambda argument v is of the struct itself and is not the Nullable type wrapper. Apparently the Nullable value that the caller uses has been resolved or 'unwrapped' by the time it hits the lambda argument and the lambda argument reveals a struct value or null; the Nullable wrapper is nowhere to be seen at this point (or as far as I can find). This behaviour can be proved by putting a debug breakpoint in the lambda at v and inspecting its value. The good side effect of this behaviour is the lambda works equally well for both Nullable and non-Nullable types -- it's not restricted.

这篇关于如何将泛型类型参数传递给lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆