struct
s (например, int
, long
и т. д.) не может принять null
по умолчанию. Таким образом, .NET предоставляет общий struct
с именем Nullable<T>
, что тип-param T
может быть от любого другого struct
s.
public struct Nullable<T> where T : struct {}
Это обеспечивает bool HasValue
свойство, указывающее, имеет ли текущий объект Nullable<T>
значение; и T Value
свойство, которое получает значение текущего Nullable<T>
значения (если HasValue == true
, в противном случае она будет бросаться InvalidOperationException
):
public struct Nullable<T> where T : struct {
public bool HasValue {
get { /* true if has a value, otherwise false */ }
}
public T Value {
get {
if(!HasValue)
throw new InvalidOperationException();
return /* returns the value */
}
}
}
И, наконец, в ответ на ваш вопрос, TypeName?
это ярлык Nullable<TypeName>
.
int? --> Nullable<int>
long? --> Nullable<long>
bool? --> Nullable<bool>
// and so on
и в использовании:
int a = null; // exception. structs -value types- cannot be null
int? a = null; // no problem
К примеру, у нас есть Table
класса, который генерирует HTML <table>
тега в методе с именем Write
. См:
public class Table {
private readonly int? _width;
public Table() {
_width = null;
// actually, we don't need to set _width to null
// but to learning purposes we did.
}
public Table(int width) {
_width = width;
}
public void Write(OurSampleHtmlWriter writer) {
writer.Write("<table");
// We have to check if our Nullable<T> variable has value, before using it:
if(_width.HasValue)
// if _width has value, we'll write it as a html attribute in table tag
writer.WriteFormat(" style=\"width: {0}px;\">");
else
// otherwise, we just close the table tag
writer.Write(">");
writer.Write("</table>");
}
}
Использование описанного выше класса -JUST как ПРИМЕР- что-то вроде этих:
var output = new OurSampleHtmlWriter(); // this is NOT a real class, just an example
var table1 = new Table();
table1.Write(output);
var table2 = new Table(500);
table2.Write(output);
И мы будем иметь:
// output1: <table></table>
// output2: <table style="width: 500px;"></table>
возможно дубликат [Почему вопросник по определению частной переменной?] (http://stackoverflow.com/questions/2326158/why-is-there-a-questionmark-on-the-private-variable-definition) –
Возможный дубликат [C# - Basic вопрос: что такое???] (http: // stackoverflo w.com/questions/2699373/c-sharp-basic-question-what-is) –