This question already has answers here:
What is the best way to clear all controls on a form C#?
(8个答案)
5年前关闭。
这样称呼它:
(8个答案)
5年前关闭。
//list the controls from the main form
foreach (Control c in Controls)
{
if (c is ComboBox)
{
((ComboBox)c).SelectedIndex = -1;
}
else if (c is TextBox)
{
((TextBox)c).Text = "";
}
else if (c is CheckBox)
{
((CheckBox)c).Checked = false;
}
//etc. with FIFTY different types to check against
}
最佳答案
使用此方法来设置控件的属性:
public void Set(object obj, string property, object value)
{
//use reflection to get the PropertyInfo of the property you want to set
//if the property is not found, GetProperty() returns null
var propertyInfo = obj.GetType().GetProperty(property);
//use the C# 6 ?. operator to only execute SetValue() if propertyInfo is not null
propertyInfo?.SetValue(obj, value);
}
这样称呼它:
foreach (Control c in Controls)
{
Set(c, "SelectedIndex", -1);
Set(c, "Text", "");
Set(c, "Checked", false);
}
关于c# - 有什么办法可以使这段代码更短?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33441355/
10-10 11:36