我有一个可为空的 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
扩展方法隐式转换string?
为string
但它不适用于其他基本类型,例如int?
orbool?
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
string? foo = "foo";
string nonNullableFoo = foo.ThrowIfNull(); …
Run Code Online (Sandbox Code Playgroud)