Skip to content
Rain Hu's Workspace
Go back

[C#] Nullable 可空值類型

Rain Hu

1. 簡寫

2. 定義

public struct Nullable<T> where struct  // 類型約束為非空值類型
{
    private readonly T value;
    private readonly bool hasValue;

    public Nullable(T value)
    {
        this.value = value;
        this.hasValue = true;
    }
    public bool HasValue { get { return hasValue; } }
    public T Value
    {
        get
        {
            if (!hasValue)
            {
                threw new InvalidOperationException();
            }
            return value;
        }
    }
}

3. 轉換

int x = 5;
int? y = x;
int? x = 5;
int y = (int)x;

4. as 運算子

public static void Main()
{
    object[] obj = new object[]{
        null,
        "3",
        '3',
        3,
        5.5
    };
    foreach (var o in obj) print(o);
}
public static void print(object o)
{
    int? num = o as int?;
    Console.WriteLine(num.HasValue ? num : "something");
}
// something
// something
// something
// 3
// something

5. ?? 運算子

int a = 5;
int? b = 10;
int? c = null;

Console.WriteLine("a + b = {0}", a + (b ?? 0));     // 15
Console.WriteLine("a + b = {0}", a + (c ?? 0));     // 5

6. ?. 運算子

List<int> a = null;
List<int> b = default;
List<int> c = new List<int>{ 1,3,5,7,9 };

Console.WriteLine(a?.Count);    //
Console.WriteLine(b?.Count);    //
Console.WriteLine(c?.Count);    // 5

Share this post on:

Previous
[C#] Delegate 委派
Next
[C#] Generic 泛型