.net 无法从“System.Guid”转换?到“System.Guid”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1988415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cannot convert from 'System.Guid?' to 'System.Guid'
提问by Dooie
Does anyone know how to deal with this error?
有谁知道如何处理这个错误?
cannot convert from 'System.Guid?' to 'System.Guid'
回答by RCIX
See MSDN.
请参阅MSDN。
In that case, merely use myNullableVariable.Value(if you're sure it has a value), or (myNullableVariable.HasValue)?myNullableVariable.Value:somedefaulthereif you're not.
在这种情况下,只需使用myNullableVariable.Value(如果您确定它有值),或者(myNullableVariable.HasValue)?myNullableVariable.Value:somedefaulthere如果您没有。
One can also use GetValueOrDefault()if one doesn't care if the default is a specific value when the nullable really is null.
GetValueOrDefault()当可空值确实为空时,如果不关心默认值是否为特定值,也可以使用。
The last way to do it is this: myNullableVariable.Value ?? defaultvalue.
最后一个办法做到这一点是这样的:myNullableVariable.Value ?? defaultvalue。
See, technically a MyType?variable is a Nullable<MyType>under the covers. There are no implicit or explicit casts between the two, so what you need to do is extract the value out of the Nullablemanually. The third way i listed is the most succinct (and best?) way to do it, to that would probably be best in most cases.
看,从技术上讲,MyType?变量是Nullable<MyType>隐藏的。两者之间没有隐式或显式转换,因此您需要做的是Nullable手动提取值。我列出的第三种方法是最简洁(也是最好的?)的方法,在大多数情况下这可能是最好的。
回答by Niraj Trivedi
Use Guid?.Value property to convert 'System.Guid?' to 'System.Guid'. as following example
使用 Guid?.Value 属性转换“System.Guid?” 到“System.Guid”。如下例
Obj GetValue(Guid yourID)
{
return FetchObject(yourID)
}
Void main()
{
Guid? passvalue;
Obj test = GetValue(passvalue.Value);
}
回答by Nigel Givans
cannot convert from 'System.Guid?' to 'System.Guid'
无法从“System.Guid”转换?到“System.Guid”
you are trying to save type System.Guid? to a type system.Guid inside your model you can edit System.Guid? to System.Guid by removing the question mark.
您正在尝试保存类型 System.Guid?到您的模型中的类型 system.Guid 您可以编辑 System.Guid 吗?通过删除问号到 System.Guid。
or RCIX answer above
或上面的 RCIX 答案
回答by Sandy
First intialize the guid variable.
首先初始化 guid 变量。
Guid yourGuid= Guid.NewGuid()
then set value in that which you want for eg:
然后设置您想要的值,例如:
Guid defaultId = Guid.NewGuid();
if (customerRow.GuardianState.Length > 2) {
Guid StateId = record.StateId ?? defaultId;}

