2 回答

TA贡献1871条经验 获得超8个赞
使用MaybeNullWhenAttribute或NotNullWhenAttribute。我推荐MaybeNullWhen,因为它甚至适用于不受结构或引用类型约束的类型参数。
public static bool TryGetValue<T>(this Option<T> option, [MaybeNullWhen(false)] out T value)
{
if (option is Some<T> some)
{
value = some.Value;
return true;
}
value = default;
return false;
}
用法:
if(option.TryGetValue(out var value))
{
value.SomeMethod(); // no warning - value is known to be non-null here
}
value.SomeMethod(); // warning - value may be null here.
该属性在 .Net 标准 2.1/.new core 3.0 之前不可用,但如果它不可用,您可以自己手动定义它。确保它是内部的,否则如果另一个库也将它定义为公共并且有人从这两个库继承它会导致冲突:
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
internal sealed class MaybeNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter may be null.
/// </param>
public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
(取自https://github.com/dotnet/runtime/blob/6077cf01f951a711a26a8d5970b211b6031b5158/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs#L45-L60)

TA贡献1801条经验 获得超16个赞
到目前为止,使用 C# 8.0 还没有完全通用的解决方案。
[NotNullWhen()]
属性是向前迈出的一步,但随后我们将遇到以下情况:
可空类型参数必须已知为值类型或不可空引用类型。考虑添加“类”、“结构”或类型约束。
我想说这是现在可以为空的一个主要痛点。我希望它会在 8.1 或其他东西中得到解决......
相关讨论 - https://github.com/dotnet/cshaplang/issues/2194 -允许泛型方法指定 T?不限于 class 或 struct。
where
作为一种解决方法,可以制作具有所需约束的多个扩展方法副本以涵盖所有可能的类型。
由于问题#1628已修复,现在可以在单个扩展类中包含所有重载。但它仍然需要为每个独立的通用输出参数增加一倍的扩展方法数量。哎呀!
- 2 回答
- 0 关注
- 253 浏览
添加回答
举报