'int?' 不包含 'TryFormat' 的定义
'int?' does not contain a definition for 'TryFormat'
我很难理解可空值类型在 C#9 中的工作原理。
以下文档来自:
- https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types
我可以写(没有编译错误):
int? a = 10;
a++; // No need for explicit 'a.Value'
但是我不能写(编译错误):
Span<char> TryFormatOrNull(int? input)
{
char[] buffer = new char[512];
if (input == null) return null;
_ = input.TryFormat(buffer, out _);
return buffer;
}
我需要写(没有语法糖):
Span<char> TryFormatOrNull(int? input)
{
char[] buffer = new char[512];
if (input == null) return null;
_ = input.Value.TryFormat(buffer, out _);
return buffer;
}
我对可空值类型与成员 function/operator 有何误解?
What did I misunderstood with nullable value types vs member function/operator ?
运算符会自动“提升”(即,非可为空值类型的运算符自动可用于相应的可为空值类型)但方法不会。就这些,真的。
查看 section 12.4.8 of the C# standard for details of lifted operators, and 11.6.2 提升的转化率。
这是因为 ++
是一个预定义的一元运算符,它可以是 "lifted"(而 TryFormat
方法不是):
The predefined unary and binary operators or any overloaded operators that are supported by a value type T
are also supported by the corresponding nullable value type T?
. These operators, also known as lifted operators, produce null
if one or both operands are null
; otherwise, the operator uses the contained values of its operands to calculate the result.
我很难理解可空值类型在 C#9 中的工作原理。
以下文档来自:
- https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types
我可以写(没有编译错误):
int? a = 10;
a++; // No need for explicit 'a.Value'
但是我不能写(编译错误):
Span<char> TryFormatOrNull(int? input)
{
char[] buffer = new char[512];
if (input == null) return null;
_ = input.TryFormat(buffer, out _);
return buffer;
}
我需要写(没有语法糖):
Span<char> TryFormatOrNull(int? input)
{
char[] buffer = new char[512];
if (input == null) return null;
_ = input.Value.TryFormat(buffer, out _);
return buffer;
}
我对可空值类型与成员 function/operator 有何误解?
What did I misunderstood with nullable value types vs member function/operator ?
运算符会自动“提升”(即,非可为空值类型的运算符自动可用于相应的可为空值类型)但方法不会。就这些,真的。
查看 section 12.4.8 of the C# standard for details of lifted operators, and 11.6.2 提升的转化率。
这是因为 ++
是一个预定义的一元运算符,它可以是 "lifted"(而 TryFormat
方法不是):
The predefined unary and binary operators or any overloaded operators that are supported by a value type
T
are also supported by the corresponding nullable value typeT?
. These operators, also known as lifted operators, producenull
if one or both operands arenull
; otherwise, the operator uses the contained values of its operands to calculate the result.