在c#中,如何转换T?到 T

0 c# nullable kotlin

类似的代码在 kotlin 中运行良好,但在 C# 中不起作用

public static class Helper
{
    public static T RequireNotNll<T>(T? obj,string? message) {
        if (obj == null) {
            throw new Exception(message ?? "obj must not null");
        }
        return obj;
    }
}
Run Code Online (Sandbox Code Playgroud)

请帮忙

Kla*_*ter 5

?对于值类型和引用类型具有不同的含义。后者仅适用于可为空的上下文( #nullable enable)。所以你需要两种方法。

对于值类型,请使用 Joel Coehoorn 提供的代码:

public static T RequireNotNull<T>(T? obj,string? message) where T : struct {
    if (!obj.HasValue) {
        throw new Exception(message ?? "obj must not be null");
    }
    return obj.Value;
}
Run Code Online (Sandbox Code Playgroud)

对于引用类型,请使用null-forgiving 运算 !符来说服编译器:

public static T RequireNotNull<T>(T? obj,string? message) where T : class {
    if (obj is null) {
        throw new Exception(message ?? "obj must not be null");
    }
    return obj!;
}
Run Code Online (Sandbox Code Playgroud)