用户定义类型选择正确的重载operator+的一般性处理例如我们在赋值语句中经常使用 a+=1 ; b-=2; c*=3; d/=3; 如果x和y是用户定义的类型, 就不能确保这样。
代码如下 :
代码如下 :
1
public class Saver : IDisposable
2
{
3
// Fields
4
private TextBox m_textBox;
5
6
private int m_start, m_end;
7
8
/// <summary>
9
/// Initializes a new instance of the Saver class by associating it with a TextBoxBase derived object. </summary>
10
/// <param name="textBox">
11
/// The TextBoxBase object for which the selection is being saved. </param>
12
/// <remarks>
13
/// This constructor saves the textbox's start and end position of the selection inside private fields. </remarks>
14
/// <seealso cref="System.Windows.Forms.TextBoxBase" />
15
public Saver(TextBox textBox)
16
{
17
m_textBox = textBox;
18
}
19
20
public static Saver operator +(Saver saver, int pos)
21
{
22
return new Saver(saver.m_textBox, saver.m_start + pos, saver.m_end + pos);
23
}
24
25
public void MoveBy(int start, int end)
26
{
27
m_start += start;
28
m_end += end;
29
30
Debug.Assert(m_start <= m_end);
31
}
32
}
33
public class Saver : IDisposable2
{3
// Fields4
private TextBox m_textBox;5

6
private int m_start, m_end;7

8
/// <summary>9
/// Initializes a new instance of the Saver class by associating it with a TextBoxBase derived object. </summary>10
/// <param name="textBox">11
/// The TextBoxBase object for which the selection is being saved. </param>12
/// <remarks>13
/// This constructor saves the textbox's start and end position of the selection inside private fields. </remarks>14
/// <seealso cref="System.Windows.Forms.TextBoxBase" /> 15
public Saver(TextBox textBox)16
{17
m_textBox = textBox;18
}19

20
public static Saver operator +(Saver saver, int pos)21
{22
return new Saver(saver.m_textBox, saver.m_start + pos, saver.m_end + pos);23
}24

25
public void MoveBy(int start, int end)26
{27
m_start += start;28
m_end += end;29

30
Debug.Assert(m_start <= m_end);31
}32
}33


浙公网安备 33010602011771号