如何从哈希表项中获取值
本文关键字:获取 哈希表 | 更新日期: 2023-09-27 18:12:54
我已经把所有的表单控件放在一个散列表中:-
foreach (Control c in this.Controls)
{
myhash.Add(c.Name, c);
}
其中有两个单选按钮。我想获得按钮的值,即选中或未选中,并将它们分配给一个变量。请问我怎样才能做到呢?谢谢大家的帮助。
foreach (Control c in hashtable.Values)
{
if(c is RadioButton)
{
string name = x.Name;
bool isChecked = (c as RadioButton).Checked;
}
}
或者如果你知道名字
(hashtable["name"] as RadioButton).Checked;
您可以通过与之关联的键来检索值,基本上control Name是您创建的哈希表中的键。所以如果你知道你需要访问的控件的名称:
var control = hash[radioButtonControlName] as RadioButton;
否则使用LINQ OfType()和List.ForEach():
// OfType() does check whether each item in hash.Values is of RadioButton type
// and return only matchings
hash.Values.OfType<RadioButton>()
.ToList()
.ForEach(rb => { bool isChecked = rb.Checked } );
OR使用foreach
环:(对List.ForEach()用法的误解有一个很好的概述)
var radioButtons = hash.Values.OfType<RadioButton>();
foreach(var button in radioButons)
{
bool isChecked = rb.Checked;
}
将作为单选按钮的控件强制转换为RadioButton class实例,然后查看选中的属性。至少这是我在WebForms中多次使用类似类完成的。
假设代码中的哈希表是hashtable的实例:
Hashtable myhash= new Hashtable();
foreach (Control c in this.Controls)
{
myhash.Add(c.Name, c);
}
你可以这样做:
foreach (DictionaryEntry entry in myhash)
{
RadioButton rb = entry.Value as RadioButton;
if (rb != null)
bool checked = rb.Checked;
}
也可以看到hashmap条目的键:
foreach (DictionaryEntry entry in myhash)
{
var componentName = entry.Key;
}
这将与您放在hashmap (c.Name)中的组件的名称相对应。