gpt4 book ai didi

c# - 默认表达式

转载 作者:太空狗 更新时间:2023-10-30 01:33:15 27 4
gpt4 key购买 nike

在C#规范中,首先是这样说的:

If the type in a default-value-expression evaluates at run-time to a reference type, the result is null converted to that type. If the type in a default-value-expression evaluates at run-time to a value type, the result is the value- type’s default value (§4.1.2).

所以看起来默认表达式是在运行时求值的……但是之后说:

A default-value-expression is a constant expression (§7.19) if the type is a reference type or a type parameter that is known to be a reference type (§10.1.5). In addition, a default-value-expression is a constant expression if the type is one of the following value types: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or any enumeration type.

那么如果只在运行时检查类型,那么默认怎么可能是一个常量表达式,从而在编译时求值?

例如,如果我这样写:

J k = default(J);

其中J是类型参数,只有在运行时,当我们提供参数类型时,才能知道J是引用类型还是值类型。那么在编译时会发生什么?

最佳答案

你只是在阅读规范错误(强调我的):

  • A default-value-expression is a constant expression (§7.19) if the type is a reference type or a type parameter that is known to be a reference type

这意味着,如果(且仅当)已知类型或类型参数是引用类型(意思是,它具有 where T : class 约束或 default(SomeClass ) 被使用),则表达式是常量。继续:

  • In addition, a default-value-expression is a constant expression if the type is one of the following value types: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or any enumeration type

意思是,出于某种原因,您正在使用 default(sbyte)default(short)

例如,给出以下代码:

void Main()
{
var x = default(byte);
var y = default(M);
}

public struct M { }

发射的 IL 将是:

IL_0000:  nop         
IL_0001: ldc.i4.0
IL_0002: stloc.0 // x
IL_0003: ldloca.s 01 // y
IL_0005: initobj UserQuery.M
IL_000B: ret

对于 byte 编译器可以发出 0,它必须为我们的 M 结构调用 initobj

关于c# - 默认表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496612/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com