![](/img/trans.png)
[英]The type 'T1' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
[英]The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
為什么我在以下代碼中收到此錯誤?
void Main()
{
int? a = 1;
int? b = AddOne(1);
a.Dump();
}
static Nullable<int> AddOne(Nullable<int> nullable)
{
return ApplyFunction<int, int>(nullable, (int x) => x + 1);
}
static Nullable<T> ApplyFunction<T, TResult>(Nullable<T> nullable, Func<T, TResult> function)
{
if (nullable.HasValue)
{
T unwrapped = nullable.Value;
TResult result = function(unwrapped);
return new Nullable<TResult>(result);
}
else
{
return new Nullable<T>();
}
}
代碼有幾個問題。 第一個是你的類型必須是可空的。 您可以通過指定where T: struct
來表達它。 您還需要指定where TResult: struct
因為您也將其用作可空類型。
一旦你修復了where T: struct where TResult: struct
你還需要改變返回值類型(這是錯誤的)和其他一些東西。
在解決了所有這些錯誤並簡化之后,你最終得到了這樣的結論:
static TResult? ApplyFunction<T, TResult>(T? nullable, Func<T, TResult> function)
where T: struct
where TResult: struct
{
if (nullable.HasValue)
return function(nullable.Value);
else
return null;
}
請注意,您可以將Nullable<T>
重寫為T?
這使事情更具可讀性。
你也可以把它寫成一個語句使用?:
但我不認為它是可讀的:
return nullable.HasValue ? (TResult?) function(nullable.Value) : null;
您可能希望將其放入擴展方法中:
public static class NullableExt
{
public static TResult? ApplyFunction<T, TResult>(this T? nullable, Func<T, TResult> function)
where T: struct
where TResult: struct
{
if (nullable.HasValue)
return function(nullable.Value);
else
return null;
}
}
然后你可以寫這樣的代碼:
int? x = 10;
double? x1 = x.ApplyFunction(i => Math.Sqrt(i));
Console.WriteLine(x1);
int? y = null;
double? y1 = y.ApplyFunction(i => Math.Sqrt(i));
Console.WriteLine(y1);
正如錯誤所示,編譯器無法保證T不會是可空的。 您需要向T添加約束:
static Nullable<T> ApplyFunction<T, TResult>(Nullable<T> nullable,
Func<T, TResult> function) : where T : struct
where TResult : struct
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.