How to Overload Get Operator in C#?
我有一个存储价值的类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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); } } |
要使用此类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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;"?
简单,添加另一个隐式运算符,但用于另一个方向!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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; } } |
使用是轻而易举的:
1 2 3 4 5 | void Main() { Entry<int> intEntry = 10; int val = intEntry; } |