2013-07-30 44 views
0

基本上,我希望能够有一个函数,它在可空类型,然后返回值,如果它有一个或字符串值“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; 
} 

回答

2
static string MyFunction<T>(Nullable<T> arg) where T : struct 
{ 
    String strNULL = "NULL"; 

    if (arg.HasValue) 
     return arg.Value.ToString(); 
    else 
     return strNULL; 
} 
+0

当然,返回 “NULL” 作为字符串的值是有争议的。如果你仍然需要处理当它为空时要做什么,那么通过将逻辑转移到方法中,你并没有获得任何东西。 –

+0

@DanielMann这只是对问题中描述的特定问题的答案。这是OP的想法返回“NULL” – empi

+1

这不会编译如:'T'需要一个非可空类型是有效的可空''(即'其中T:struct') – RoadieRich