2017-06-15 5 views
0

私は値を格納するクラスを持っています。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; } 
} 

私は "= 1 ID" を行うことができますstraightaway集合演算子をオーバーロードすることができますよ。

しかし、私が "int tempID = ID;"を実行すると、エラーが発生します。

get operatorをオーバーロードして「int tempID = ID;」を実行する方法代わりに "int tempID = ID.Value;"?

+0

あなたはそれがintを等しくすることができるように、エントリ・タイプに演算子を追加する必要があるとしています。 –

+1

さて、私がコメントを残すとすぐに、誰かが例を投稿します。笑 –

答えて

3

シンプルに、別の暗黙の演算子を追加しますが、もう一方の方向は追加してください!

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

ありがとうございます! – lim0721lim

関連する問題