我在某些情况下(例如,保存 Sql 参数的自定义类)可能需要也可能不需要变量。传统上,我总是定义这些类型Guid?
并用于myGuid.HasValue
在使用前检查有效值。
当然,在实践中,我也可以使用常规Guid
s 并使用myGuid == Guid.Empty
.
为了可读性,我更喜欢第一种用法,因为它感觉更干净,但如果有人能就这些方法中的一种是否比另一种更好(更快、更快或更正确)提出建议,我将不胜感激?
我在某些情况下(例如,保存 Sql 参数的自定义类)可能需要也可能不需要变量。传统上,我总是定义这些类型Guid?
并用于myGuid.HasValue
在使用前检查有效值。
当然,在实践中,我也可以使用常规Guid
s 并使用myGuid == Guid.Empty
.
为了可读性,我更喜欢第一种用法,因为它感觉更干净,但如果有人能就这些方法中的一种是否比另一种更好(更快、更快或更正确)提出建议,我将不胜感激?
If the parameter can be null on the T-Sql side, then I think Guid?
is a more natural fit. Especially when used with ADO.NET parameterized queries, nullable types are conveniently translated to DBNull.Value
when their value is null
. If you were to use Guid.Empty
to indicate null, then you'd need to check for that condition and explicitly pass DBNull.Value
to your command/query. E.g.:
command.Parameters.AddWithValue("@guid", myNullableGuid)
vs.
command.Parameters.AddWithValue("@guid",
myGuid == Guid.Empty ? DBNull.Value : myGuid)
There is virtually no performance difference between the two alternatives, otherwise.
I think that approach with Guid?
is much more better. It just a coincidence that a default value of Guid
whuch is equal to Guid.Empty
has no real usage and can be treated as null
value. For example, int
or bool
default values are used without any distinction with other values.
So, IMHO, you should use Guid?
to stay consistent.
我通常使用如下声明:
Guid? objGuidStudent = null;
objGuidStudent = Students.FindByName('Oscar');
Classrooms.Add(x, y, z, objGuidStudent);
无论有无 NULL 值,它都能完美运行。