返回从泛型方法空值 [英] Returning null value from generic method

查看:246
本文介绍了返回从泛型方法空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这样的方法:

    internal K GetValue<T, K>(T source, string col) where T : IBaseObject
    {
        string table = GetObjectTableName(source.GetType());
        DataTable dt = _mbx.Tables[table];
        DataRow[] rows = dt.Select("ID = " + source.ID);
        if (rows.Length == 0) return K;

        return (K) rows[0][col];
    }

我希望能够返回空,或者某种空值,如果没有行被发现。什么是正确的语法来做到这一点?

I want to be able to return a null, or some kind of empty value, if no rows are found. What's the correct syntax to do this?

推荐答案

您可以返回默认值(K),这意味着你将返回null如果K是引用类型,或者为0,INT,'\ 0'字符等...

You could return default(K), and that means you will return null if K is a reference type, or 0 for int, '\0' for char, and so on...

然后就可以轻松地验证这是否是返回:

Then you can easily verify if that was returned:

if (object.Equals(resultValue, default(K)))
{
    //...
}

这篇关于返回从泛型方法空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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