【发布时间】:2022-01-22 13:52:40
【问题描述】:
我有一个可以为空的 c# 10 .net 6 项目,其扩展方法为 ThrowIfNull
using System;
using System.Runtime.CompilerServices;
#nullable enable
public static class NullExtensions
{
public static T ThrowIfNull<T>(
this T? argument,
string? message = default,
[CallerArgumentExpression("argument")] string? paramName = default
)
{
if (argument is null)
{
throw new ArgumentNullException(paramName, message);
}
else
{
return argument;
}
}
}
扩展方法将string?隐式转换为string,但它不适用于int?或bool?等其他原始类型
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
string? foo = "foo";
string nonNullableFoo = foo.ThrowIfNull(); // success from "string?" to "string"
Console.WriteLine(nonNullableFoo);
bool? baz = true;
bool nonNullableBaz = baz.ThrowIfNull(); // success from "string?" to "string"
Console.WriteLine(nonNullableFoo);
int? bar = 2;
int nonNullableBar = bar.ThrowIfNull(); // error: Cannot implicitly convert type 'int?' to 'int'
Console.WriteLine(nonNullableBar);
}
}
如何使扩展隐式转换int? 和bool??
这是完整的 dotnet fiddle https://dotnetfiddle.net/LiQ8NL
【问题讨论】: