函数接受可为null的类型并返回可为null类型或字符串

本文关键字:类型 null 返回 字符串 函数 | 更新日期: 2023-09-27 18:25:27

基本上,我希望能够有一个函数,它接受一个可为NULL的类型,然后如果它有一个值,则返回该值;如果它为NULL,则返回字符串值"NULL",因此该函数需要能够接受任何可为NULL类型,然后返回该类型或返回字符串NULL。下面是我想要的一个例子,我似乎不知道我的职能需要做什么。

UInt16? a = 5;
UInt16? b = null;
UInt32? c = 10;
UInt32? d = null;
Console.WriteLine(MyFunction<UInt16?>(a)) // Writes 5 as UInt16?
Console.WriteLine(MyFunction(UInt16?>(b)) // Writes NULL as String
Console.WriteLine(MyFunction(UInt32?>(c)) // Writes 10 as UInt32?
Console.WriteLine(MyFunction(UInt32?>(d)) // Writes NULL as String
static T MyFunction<T>(T arg)
{
    String strNULL = "NULL";
    if (arg.HasValue)
        return arg;
    else
        return strNULL;
}

函数接受可为null的类型并返回可为null类型或字符串

static string MyFunction<T>(Nullable<T> arg) where T : struct
{
    String strNULL = "NULL";
    if (arg.HasValue)
        return arg.Value.ToString();
    else
        return strNULL;
}