C# - Basic question: What is '?'? [duplicate]

瘦欲@ 提交于 2019-12-17 16:16:47

问题


I'm wondering what ? means in C# ?
I'm seeing things like: DateTime? or int?. I suppose this is specific to C# 4.0?
I can't look for it in Google because I don't know the name of this thing.
The problem is I'm using DateTime and I have a lot of cast errors (from DateTime to DateTime?).

Thank you


回答1:


It's a shorthand for writing Nullable<int> or Nullable<DateTime>. Nullables are used with value types that cannot be null (they always have a value).

It is not specific to C#4 by the way.

You can only assign an int? to an int if it has a value, so your code would have to do things like:

int? n = 1;
int i = n ?? default(int); //or whatever makes sense

Also note that a Nullable has two properties, HasValue and Value that you can use test if a value has been set and to get the actual value.




回答2:


It means it's a nullable type.

It allows you to assign a null value to value types such as int and DateTime. It's very helpful with things like optional fields in a database.




回答3:


It designates nullable types.

I suppose this is C# specific to C# 4.0?

It has been in C# since 2.0




回答4:


The ? is a nullable value type.

You can use the ?? operator to mix it with value types:

const int DefaultValue = -1;

// get a result that may be an integer, or may be null
int? myval = GetOptionalIdFromDB();

// the value after ?? is used if myval is null
int nonNullable = myval ?? DefaultValue;

The nullable type can be compared to null, so the above is shorthand for:

if( myval != null ) {
    nonNullable = myval.Value;
} else {
    nonNullable = DefaultValue;
}

But I prefer ??




回答5:


A gotcha to look out for: [edit: apparently this only happens sometimes]

// nullable type properties may not initialize as null
private int? foo; // foo = 0

// to be certain, tell them to be null
private int? foo = null;



回答6:


It is a shorthand way of declaring an implementation of the generic class Nullable<T>, where T is a non-nullable value type.

So

int? i = null;

is the same as

Nullable<int> i = null;

As mentioned above Nullable<T> exposes the HasValue property so you can check if i has a value before working on it.

Interesting to note: If you cast Nullable<int> i = 3; to an object, you can cast back to an int or a Nullable<int> because it had a value before boxing. If, however you cast Nullable<int> i = null; to an object you will get a NullReferenceException when casting back to an int but you can cast back to a Nullable<int>.




回答7:


As others have said, after the name of a type it means the nullable type.

? is also used in the condition operator.

int max = x > y ? x : y

This is equivalent to:

int max;
if( x > y )
{
  max = x;
}
else
{
  max = y;
}


来源:https://stackoverflow.com/questions/2699373/c-sharp-basic-question-what-is

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!