[英]Get Checked Value for Both RadioButtons and CheckBoxes in C#
所以我有一個事件,可以通過更改某些復選框和某些單選按鈕的選中值來觸發。 我想獲取觸發事件的控件的Checked值。 我知道,如果這是一個復選框,我可以執行類似bool checkedValue = (sender as CheckBox).Checked;
(與單選按鈕相同)。 但是如果我不知道控件的類型怎么辦? 他們倆都有上課嗎?
如果您正在運行.NET 4,則可能要嘗試以下丑陋技巧:
private void checkBox1_Click(dynamic sender, EventArgs e) {
bool isChecked = sender.Checked;
textBox1.Text = isChecked ? "Checked" : "Unchecked";
}
不是很安全,但是很有趣!
它們都是從ButtonBase
派生的,但是ButtonBase
沒有實現IsChecked
。 建議創建兩個CheckBox
和RadioButton
子類,聲明一個接口,即IHasCheck
,在派生類中正確實現它,然后嘗試在事件處理程序中將此接口IHasCheck
為:
public interface ICheckable
{
bool Checked { get; set; }
}
class RadioButtonExtended : RadioButton,ICheckable
{
}
class CheckBoxExtended : CheckBox, ICheckable
{
}
您可以構建一個帶有控制參數的小函數。 然后嘗試首先強制轉換為Check box,如果不為null,則使用Checked結果。 如果為null,請使用單選按鈕嘗試相同的操作。 如果也為null,則拋出InvalidParameterException或適當的內容。 否則返回您保存的值。
bool GetChecked(object ctrl) {
bool result = false;
CheckBox cb = ctrl as CheckBox;
if ( null == cb ) {
RadioButton rb = ctrl as RadioButton;
if ( null == rb ) {
throw new Exception ( "ctrl is of the wrong type " );
}
result = rb.Checked;
} else {
result = cb.Checked;
}
return result;
}
沒有嘗試編譯,只是提供了想法。 第二個想法:做一點思考,看看是否有一個名為Checked的屬性並獲取該值。 未經測試的粗糙代碼:
bool GetChecked(object ctrl) {
bool result = false;
Type reflectedResult = ctrl.GetType();
PropertyInfo[] properties = reflectedResult.GetProperties();
List<System.Reflection.PropertyInfo> properties = ctrl.GetProperties ().Where ( itm => itm.Name == "Checked" ).ToList ();
if ( properties.Count == 1 )
{
bool result = (bool)properties[0].GetValue ( ctrl, null );
} else {
throw new Exception ( "ctrl is of the wrong type " );
}
return result;
}
雖然我不喜歡兩者的代碼...
最好的方法是使用界面,但是根據您對Felice Pollano答案的評論,您不想這樣做。
然后,我建議在運行時查找類型:
bool checked;
if (sender is CheckBox)
checked = ((CheckBox)sender).Checked;
if (sender is RadioButton)
checked = ((RadioButton)sender).Checked;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.