C# 使不可为空的值类型可以为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/596003/
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
Making a Non-nullable value type nullable
提问by Malfist
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.
我有一个使用有限的简单结构。该结构是在从数据库调用数据的方法中创建的。如果没有从数据库返回的数据,我希望能够返回 null,但 Visual Studio 会抱怨,无法将 null 转换为 PackageName.StructName,因为它是不可为 null 的值类型。
How can I make it nullable?
我怎样才能使它可以为空?
采纳答案by Andrew Hare
You want to look into the Nullable<T>
value type.
您想查看Nullable<T>
值类型。
回答by mqp
public struct Something
{
//...
}
public static Something GetSomethingSomehow()
{
Something? data = MaybeGetSomethingFrom(theDatabase);
bool questionMarkMeansNullable = (data == null);
return data ?? Something.DefaultValue;
}
回答by Orion Adrian
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.
Nullable<T>
是一个包装类,它创建类型 T 的可为空版本。您还可以使用语法 T? (例如 int?)来表示类型 T 的可为空版本。
回答by John Rasch
The definition for a Nullable<T>
struct is:
Nullable<T>
结构体的定义是:
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
请参阅:MSDN
回答by Jake
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.
}
回答by Levite
Use the built-in shortcutsfor the Nullable<T>
struct, by simply adding ?
to the declaration:
使用内置的快捷方式的Nullable<T>
结构,通过简单地添加?
的声明:
int? x = null;
if (x == null) { ... }
Just the same for any other type, struct, etc.
对于任何其他类型、结构等都一样。
MyStruct? myNullableStruct = new MyStruct(params);
回答by prakash yadav
You can use defaultas an alternative
您可以使用默认值作为替代
public struct VelocityRange
{
private double myLowerVelocityLimit;
private double myUpperVelocityLimit;
}
VelocityRange velocityRange = default(VelocityRange);
VelocityRange velocityRange =默认(VelocityRange);