Note: textbox4sql is an idiot. This problem should be maintained at the SQL layer rather than on the UI.
For so long, oop seldom uses the new keyword "hide" members of the parent class. One day, the text attribute of a textbox needs to be modified. Since the SQL syntax is called in the original code, textbox is directly called. the text attribute is used to merge varchar data into SQL statements. It never filters out special characters for strings. Therefore, I entered "'" (single quotation marks) in a text box ), as a result, SQL is abnormal. However, this SQL call method is everywhere in the Code. Therefore, we plan to recreate textbox so that when reading the text attribute, we can replace the first single quotation mark with two, make the SQL syntax correct. The first textbox4sql class:
- Using system. Windows. forms;
- Namespace windowsformsapplication1
- {
- Public class textbox4sql: textbox
- {
- Public override string text
- {
- Get
- {
- Return base. Text. Replace ("'","''");
- }
- Set
- {
- Base. Text = value;
- }
- }
- Public String RealText
- {
- Get
- {
- Return base. text;
- }
- Set
- {
- Base. Text = value;
- }
- }
- }
- }
The text attribute of the parent class is overwritten, so that each of the single quotes is replaced with two single quotes (11 rows ). However, sometimes the original text content needs to be obtained, so a new RealText attribute is written and the text attribute content of the parent class is directly returned (24 rows ). Unfortunately, we use the override keyword to override the parent text attribute. The content returned by RealText will be processed by 11th lines of code. Obviously, I should use the new keyword instead of override rewriting text.
The New Keyword overwrites the text property of the textbox4sql class inherited by the parent class, but the text (base. text) is still valid. This is different from override. If the parent class uses the virtual keyword to modify, it wants the override of the quilt class to be overwritten. rewriting means the effect is completely replaced. Therefore, if you replace override with new, the override of the text attribute overwrites it, you can make the RealText attribute return the original text content of the parent class. Or we want the RealText attribute to be overwritten by the quilt class. Add the virtual keyword.
- Using system. Windows. forms;
- Namespace windowsformsapplication1
- {
- Public class textbox4sql: textbox
- {
- Public New String text
- {
- Get
- {
- Return base. Text. Replace ("'","''");
- }
- Set
- {
- Base. Text = value;
- }
- }
- Public Virtual string RealText
- {
- Get
- {
- Return base. text;
- }
- Set
- {
- Base. Text = value;
- }
- }
- }
- }
It also needs to be explained that new can hide members of any parent class. Override can be rewritten by virtual, abstract, or override modified members, so we call override as rewrite.