问题
I have a simple struct that has limited use. The struct is created in a method that calls the data from the database. If there is no data returned from the database I want to be able to return a null, but Visual Studio complains, Cannot convert null to PackageName.StructName because it is a non-nullable value type.
How can I make it nullable?
回答1:
You want to look into the Nullable<T> value type.
回答2:
public struct Something
{
//...
}
public static Something GetSomethingSomehow()
{
Something? data = MaybeGetSomethingFrom(theDatabase);
bool questionMarkMeansNullable = (data == null);
return data ?? Something.DefaultValue;
}
回答3:
The definition for a Nullable<T>
struct is:
struct Nullable<T>
{
public bool HasValue;
public T Value;
}
It is created in this manner:
Nullable<PackageName.StructName> nullableStruct = new Nullable<PackageName.StructName>(params);
You can shortcut this mess by simply typing:
PackageName.StructName? nullableStruct = new PackageName.StructName(params);
See: MSDN
回答4:
Nullable<T> is a wrapper class that creates a nullable version of the type T. You can also use the syntax T? (e.g. int?) to represent the nullable version of type T.
回答5:
Use the built-in shortcuts for the Nullable<T>
struct, by simply adding ?
to the declaration:
int? x = null;
if (x == null) { ... }
Just the same for any other type, struct, etc.
MyStruct? myNullableStruct = new MyStruct(params);
回答6:
You could make something nullable for example like this:
// Create the nullable object.
int? value = new int?();
// Check for if the object is null.
if(value == null)
{
// Your code goes here.
}
回答7:
You can use default as an alternative
public struct VelocityRange
{
private double myLowerVelocityLimit;
private double myUpperVelocityLimit;
}
VelocityRange velocityRange = default(VelocityRange);
来源:https://stackoverflow.com/questions/596003/making-a-non-nullable-value-type-nullable