返回从泛型方法空值方法

2023-09-03 07:49:54 作者:念一季花落i

所以我有这样的方法:

    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)))
{
    //...
}