小编Ssh*_*ack的帖子

如何将可空类型隐式转换为不可空类型

我有一个可为空的 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)

.net c#

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

.net ×1

c# ×1