有人知道如何处理这个错误吗?
cannot convert from 'System.Guid?' to 'System.Guid'
参见MSDN。
在这种情况下,如果您确定可空变量具有值,则仅使用myNullableVariable.Value
,否则使用(myNullableVariable.HasValue)?myNullableVariable.Value:somedefaulthere
。
如果您不关心默认值是否为特定值,则可以使用GetValueOrDefault()
,当可空类型真正为空时。
最后一种方法是:myNullableVariable.Value ?? defaultvalue
。
实际上,MyType?
变量在内部是一个Nullable<MyType>
。它们之间没有隐式或显式转换,因此需要手动从Nullable
中提取值。我列出的第三种方式最简洁(也是最好的?)方式,因此在大多数情况下可能是最好的选择。
Obj GetValue(Guid yourID)
{
return FetchObject(yourID)
}
Void main()
{
Guid? passvalue;
Obj test = GetValue(passvalue.Value);
}
只需在if语句中使用Nullable<T>.HasValue
来检查null值,然后在其后使用Nullable<T>.Value
来获取基础类型的值。
int? a = null;
if(a.HasValue){
Console.WriteLine($"a has value {a.Value}");
} else {
Console.WriteLine("No value found in a");
}
Guid yourGuid= Guid.NewGuid()
Guid defaultId = Guid.NewGuid();
if (customerRow.GuardianState.Length > 2) {
Guid StateId = record.StateId ?? defaultId;}