【问题标题】:How to Overload Get Operator in C#?如何在 C# 中重载获取运算符?
【发布时间】:2017-06-15 03:30:58
【问题描述】:

我有一个存储值的类。

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

我能够重载集合运算符,我可以直接执行“ID = 1”。

但是当我执行“int tempID = ID;”时,它会抛出错误。

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

【问题讨论】:

  • 您将不得不向 Entry 类型添加一个运算符,以便它可以等于 int。
  • 好吧,我一发表评论,就会有人发布示例。大声笑

标签: c# operator-overloading


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 2012-02-10
    • 2011-11-09
    • 1970-01-01
    • 2012-10-20
    相关资源
    最近更新 更多