【发布时间】:2014-12-01 14:35:02
【问题描述】:
让我们使用以下代码:
int? a = null;
int b = (int)a;
并提取CastExpressionSyntax 为(int)a 表达式。
没有转化:
semanticModel.GetConversion(node) == {Identity}
没有符号(我希望是Nullable<T>implicit operator T)
semanticModel.GetSymbolInfo(node).Method == null
类型信息的两个值相同
semanticModel.GetTypeInfo(node) == {Type = Int32, ConvertedType = Int32}
semanticModel.GetTypeInfo(node.Expression) == {Type = Int32?, ConvertedType = Int32?}
是否有正确的方法来检测可空到不可空的强制转换,或者我需要手动查看其中一个类型信息是否可以为空而另一个不是?
不同行为的示例:
让我们来看看结构:
public struct N<T> where T : struct
{
public static explicit operator T(N<T> value)
{
return default(T);
}
}
并且在之前像 nullable 一样使用它
N<int> e;
int d = (int) e;
@Kirk Woll 说得对,GetConversion 和 GetTypeInfo 是一样的,但 GetSymbolInfo 会返回 public static explicit operator T(N<T> value) 方法。
Nullable 具有完全相同的方法,但没有返回。
没有对操作员的调用 emmited 编译器生成对 Value 属性的直接调用。
IL_0001: ldloca.s 00 // a
IL_0003: initobj System.Nullable<System.Int32>
IL_0009: ldloca.s 00 // a
IL_000B: call System.Nullable<System.Int32>.get_Value
IL_0010: stloc.1 // b
【问题讨论】:
-
node和node.Expression的类型信息不给你答案吗? -
@KirkWoll,它确实,有点,但通常转换是存在的,所以我想知道这个案例有什么特别之处