【发布时间】: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。
-
好吧,我一发表评论,就会有人发布示例。大声笑