簡體   English   中英

獲取控件的“值”屬性

[英]Getting the “value” property of a control

我有一個具有Control參數的方法。 我想獲取控件的值。 因此,如果它是一個TextBox獲取Text屬性的值; 如果是NumericUpDown獲取Value屬性的Value ,依此類推。

問題是我不能寫這樣的東西:

Method(Control control)
{
    control.Text;
}

要么

Method(Control control)
{
    control.Value;
}

因為不能保證控件具有這些屬性之一,並且擁有控件的名稱是什么。 有沒有辦法做這樣的事情?

Control類中沒有這樣的通用Value屬性。

您應該使用一些if / else或switch / case或Dictionary方法來從控件中獲取值。 因為您知道您需要什么財產。 該控件僅提供屬性。

例如對於ComboBox ,值是什么? SelectedItemSelectedIndexSelectedValueText嗎? 它基於使用情況/意見。

與您要查找的內容最接近的是,依靠控件的DefaultProperty屬性使用relfection從該屬性獲取值。 例如,使用此方法:

public object GetDefaultPropertyValue(Control c)
{
    var defaultPropertyAttribute = c.GetType().GetCustomAttributes(true)
        .OfType<DefaultPropertyAttribute>().FirstOrDefault();
    var defaultProperty = defaultPropertyAttribute.Name;
    return c.GetType().GetProperty(defaultProperty).GetValue(c);
}

您可以通過以下方式獲取值:

var controls = new List<Control> {
    new Button() { Text = "button1" },
    new NumericUpDown() { Value = 5 },
    new TextBox() { Text = "some text" },
    new CheckBox() { Checked = true }
};

var values = controls.Select(x => GetDefaultPropertyValue(x)).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM