簡體   English   中英

如何重載C#中的Get運算符?

[英]How to Overload Get Operator in C#?

我有一堂課可以儲存價值。

public class Entry<T>
{
    private T _value;

    public Entry() { }    

    public Entry(T value)
    {
        _value = value;
    }

    public T Value
    {
        get { return _value; }
        set { _value = value; }
    }

    // overload set operator.
    public static implicit operator Entry<T>(T value)
    {
        return new Entry<T>(value);
    }
}

要使用此類:

public class Exam
{
    public Exam()
    {
        ID = new Entry<int>();
        Result = new Entry<int>();

        // notice here I can assign T type value, because I overload set operator.
        ID = 1;
        Result = "Good Result.";

        // this will throw error, how to overload the get operator here?
        int tempID = ID;
        string tempResult = Result;

        // else I will need to write longer code like this.
       int tempID = ID.Value;
       string tempResult = Result.Value;
    }

    public Entry<int> ID { get; set; }
    public Entry<string> Result { get; set; } 
}

我可以重載set操作符,可以直接執行“ ID = 1”。

但是當我執行“ int tempID = ID;”時,它將引發錯誤。

如何重載get運算符,以便可以執行“ int tempID = ID;” 而不是“ int tempID = ID.Value;”?

很簡單,為另一個方向添加另一個隱式運算符!

public class Entry<T>
{
    private T _value;

    public Entry() { }

    public Entry(T value)
    {
        _value = value;
    }

    public T Value
    {
        get { return _value; }
        set { _value = value; }
    }

    public static implicit operator Entry<T>(T value)
    {
        return new Entry<T>(value);
    }

    public static implicit operator T(Entry<T> entry)
    {
        return entry.Value;
    }
}

使用起來輕而易舉:

void Main()
{
    Entry<int> intEntry = 10;
    int val = intEntry;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM