如何在C#中重载运算符?

时间:2017-06-15 03:30:59

标签: c# operator-overloading

我有一个存储价值的课程。

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操作符,我可以直接做&#34; ID = 1&#34;。

但是当我做&#34; int tempID = ID;&#34;时,它会抛出错误。

如何重载get运算符以便我可以执行&#34; int tempID = ID;&#34;而不是&#34; int tempID = ID.Value;&#34;?

1 个答案:

答案 0 :(得分:3)

简单,添加另一个隐式运算符,但另一个方向!

AVPlayerLayer

使用方法轻而易举:

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;
    }
}