c#:IsNullableType助手类?

mar*_*ith 1 c#

有人可以帮忙吗?

我有一些代码在两个项目之间共享.代码指向一个模型,该模型基本上是来自db的属性集合.

问题在于某些属性在1个模型中使用可空类型而另一个属性则不在

真的dbs应该使用相同,但他们不..

所以例如有一个名为IsAvailble的属性,它在一个模型中使用"bool"而另一个使用bool?(可空类型)

所以在我的代码中我做了以下几点

 objContract.IsAvailble.Value ? "Yes" : "No"   //notice the property .VALUE as its a bool? (nullable type)
Run Code Online (Sandbox Code Playgroud)

但是这条线在使用标准"bool"(不可为空)的模型上会失败,因为在不可为空的类型上没有属性.VALUE

是否有某种辅助类,我检查属性是否为可空类型,我可以返回.Value ..否则我只是返回属性.

有人有解决方案吗?

编辑

这就是我现在所拥有的.....我正在检查可空类型版本中的HasValue

public static class NullableExtensions {public static T GetValue(this T obj)其中T:struct {return obj; public static T GetValue(this Nullable obj)其中T:struct {return obj.Value; }

    public static T GetValue<T>(this T obj, T defaultValue) where T : struct
    {
        return obj;
    }

    public static T GetValue<T>(this Nullable<T> obj, T defaultValue) where T : struct
    {
        if (obj.HasValue)
            return obj.Value;
        else
            return defaultValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

Kob*_*obi 5

这有点奇怪,但也许你可以在这里使用扩展方法:

static class NullableExtensions
{
    public static T GetValue<T>(this T obj) where T : struct
    {
        return obj;
    }
    public static T GetValue<T>(this Nullable<T> obj) where T : struct
    {
        return obj.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

他们将使用可空或常规类型:

int? i = 4;
int j = 5;

int a = i.GetValue();
int b = j.GetValue();
Run Code Online (Sandbox Code Playgroud)

  • +1对于灵活性,因为如上所述,bool可能不是唯一的类型. (2认同)