在c#中调用两次构造函数 [英] call contructor twice in c#

查看:321
本文介绍了在c#中调用两次构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个程序就像记事本一样有胜利形式。



我想打开一些txt文件,并显示它们。



我有一个名为DirtyCheckingTextBox的类,它派生自TextBox,

我在表单中使用DirtyCheckingTextBox tbxContent来显示文本。


openMenu点击事件中的


I wrote a program works like the notepad with win form.

I want to open some txt file, and display them.

I have a class called DirtyCheckingTextBox which derived from TextBox,
I use the DirtyCheckingTextBox tbxContent in the form to display text.

in the openMenu click event :

{
  // .. openfiledialog stuff
  var content = FileServices.GetContent(fileName); // get the txt content
  tbxContent = new DirtyCheckingTextbox(content);
}





构造函数:





the Constructor:

 public DirtyCheckingTextbox() : this(String.Empty)
 {
 }

public DirtyCheckingTextbox(string initialText)
{
    this.Text = initialText;
    this.CleanText = this.Text;
}





但问题是我发现调试窗口tbxContent.Text有txt文件内容,但表单不显示文本,为什么?



默认情况下tbxContent调用默认构造函数,我想问题可能是我再次调用构造函数新的DirtyCheckingTextbox(内容);



but the problem is that I found the the debug window the tbxContent.Text has the txt files content, but the form doesn't display the text, why?

by default the tbxContent call the default constructor, I think the problem maybe I call the constructor again new DirtyCheckingTextbox(content);

推荐答案

正如RyanDev所说,需要将testbox添加到表单中。



As RyanDev said the testbox needs to be added to the form.

TextBox DirtyCheckingTextbox= new TextBox();
DirtyCheckingTextbox.Location = new Point(200, 200);
this.Controls.Add(DirtyCheckingTextbox);
DirtyCheckingTextbox.Text = content ;





祝你好运。



Good luck.


问题是你正在创建一个新的DirtyCheckingTextbox的实例并将其分配给tbxContent变量 - 它不显示它,或者更新已经在显示器上的版本。



相反,移动你的将代码编入方法,并调用:

The problem is that you are creating a new instance of the DirtyCheckingTextbox and assigning it to the tbxContent variable - which doesn't display it, or update the version which is already on the display.

Instead, move your code into a method, and call that:
public DirtyCheckingTextbox() : this(String.Empty)
    {
    }
    
public DirtyCheckingTextbox(string initialText)
    {
    Reset(initialText);
    }

public void Reset(string initialText)
    this.Text = initialText;
    this.CleanText = this.Text;
    }




{
// .. openfiledialog stuff
var content = FileServices.GetContent(fileName); // get the txt content
tbxContent.Reset(content);
}





类型 - 非常奇怪的拼写错误 - OriginalGriff [/ edit]



[edit]Types - very odd typos - OriginalGriff[/edit]


这篇关于在c#中调用两次构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆