哪种方法是清除文本框值的最佳方法? [英] Which method is best way to clear the textbox values?
问题描述
方法1:
public void ClearControlValues()
{
txtHolidayDate.Text = string。空;
txtHolidayName.Text = string.Empty;
txtHolidayDescription.Text = string.Empty;
}
方法2:
public void ClearControlValues()
{
txtHolidayDate.Text = txtHolidayName.Text = txtHolidayDescription.Text = string.Empty;
}
我尝试了什么:
哪种方法是清除文本框值的最佳方法
这是一个风格问题。如果您的雇主没有已发布的编码样式:
0)如果您正在编辑现有文件,请使用该文件中使用的样式。 br />
1)如果它是你正在创建的新文件,请按照你喜欢的方式进行。
就个人而言,我更喜欢每行一个作业,但那就是我。
我同意约翰。这两个版本编译成大致相同的IL,所以这只是一个偏好问题。
看看方法二,你可能会期望它做类似的事情:
txtHolidayDescription.Text = string .Empty;
txtHolidayName.Text = txtHolidayDescription.Text;
txtHolidayDate.Text = txtHolidayName.Text;
但是如果你检查编译的IL,你会看到属性get
永远不会调用访问者。相反,你只需得到:
txtHolidayDescription.Text = string .Empty;
txtHolidayName.Text = string .Empty;
txtHolidayDate.Text = string .Empty;
您可以使用简单的类演示:
public class Foo
{
public string 文字
{
get { throw new InvalidOperationException( 嘘!); }
set {}
}
}
static class 计划
{
static void Main()
{
Foo x = new Foo();
Foo y = new Foo();
Foo z = new Foo();
x.Text = y.Text = z.Text = Hello;
Console.WriteLine( Hooray!);
}
}运行该代码时,不会抛出任何异常,这表明不会调用
get
访问器。 / BLOCKQUOTE>
Method 1 :
public void ClearControlValues()
{
txtHolidayDate.Text = string.Empty;
txtHolidayName.Text = string.Empty;
txtHolidayDescription.Text = string.Empty;
}
Method2:
public void ClearControlValues()
{
txtHolidayDate.Text = txtHolidayName.Text = txtHolidayDescription.Text = string.Empty;
}
What I have tried:
Which method is best way to clear the textbox values解决方案It's a matter of style. If your employer doesn't have a published coding style:
0) If you're editing an existing file, use the style that is used in that file.
1) If it's a new file that you're creating, do it the way that you prefer.
Personally, I prefer one assignment per line, but that's me.
I agree with John. Both versions compile to roughly the same IL, so it's just a matter of preference.
Looking at method two, you might expect it to do something like:
txtHolidayDescription.Text = string.Empty; txtHolidayName.Text = txtHolidayDescription.Text; txtHolidayDate.Text = txtHolidayName.Text;
But if you examine the compiled IL, you'll see that the propertyget
accessor is never called. Instead, you simply get:
txtHolidayDescription.Text = string.Empty; txtHolidayName.Text = string.Empty; txtHolidayDate.Text = string.Empty;
You can demonstrate this with a simple class:
public class Foo { public string Text { get { throw new InvalidOperationException("Boo!"); } set { } } } static class Program { static void Main() { Foo x = new Foo(); Foo y = new Foo(); Foo z = new Foo(); x.Text = y.Text = z.Text = "Hello"; Console.WriteLine("Hooray!"); } }Running that code, no exception is thrown, which demonstrates that the
get
accessor is not called.
这篇关于哪种方法是清除文本框值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!