提问人:Khosro 提问时间:11/7/2023 最后编辑:Denis MichealKhosro 更新时间:11/8/2023 访问量:41
如何在使用反射时在 C# 中创建 List<T> 实例 [duplicate]
How to create List<T> instance in C# when using reflection [duplicate]
问:
我有一个类,其中包含一些通用属性以及一些其他类型的属性:
private ObservableCollection<SelectFood> _breakfasts = new ObservableCollection<SelectFood>();
public ObservableCollection<SelectFood> Breakfasts
{
get { return _breakfasts; }
set { SetProperty(ref _breakfasts, value); }
}
private ObservableCollection<SelectFood> _lunches = new ObservableCollection<SelectFood>();
public ObservableCollection<SelectFood> Lunches
{
get { return _lunches; }
set
{ SetProperty(ref _lunches, value); }
}
private TblDailyFoodList _foodinfo = new TblDailyFoodList();
public TblDailyFoodList Foodinfo
{
get { return _foodinfo; }
set { SetProperty(ref _foodinfo, value); }
}
SelectFood
是一个带有一些字段、属性和......userControl
现在,在一个方法中,我想遍历这个类的属性,如果属性是类型,根据它的名称,做一些工作:ObservableCollection<SelectFood>
private void SelectedFoods()
{
PropertyInfo[] properties = typeof(DailyFoodListViewModel).GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(ObservableCollection<SelectFood>))
{
foreach (var item in property)
{
if (item.IsChkbxChecked == true)
{
Foodinfo.Foods += item.MyTblFoodInfo.FoodType + string.Format(item.MyTblFoodInfo.Id.ToString("000"));
}
}
break;
}
}
}
现在我的问题:
在循环中,我不能直接使用。
如何在foreach循环中使用?foreach (var item in property)
property
property
答:
0赞
RoadieRich
11/8/2023
#1
C# 是一种静态类型语言。使用反射来构建你的列表会失去很多好处。
相反,由于几乎可以肯定知道存在什么,您可能应该做这样的事情:ObservableCollections
var list = new List<SelectFood>();
list.Concat(Breakfasts);
list.Concat(Lunches);
//... for each meal
return result;
如果你绝对必须使用反射,你需要调用 ,像这样:property.GetValue
private void SelectedFoods()
{
PropertyInfo[] properties = typeof(DailyFoodListViewModel).GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(ObservableCollection<SelectFood>))
{
foreach (var item in (ObservableCollection<SelectFood>)property.GetValue(this))
{
if (item.IsChkbxChecked == true)
{
Foodinfo.Foods += item.MyTblFoodInfo.FoodType + string.Format(item.MyTblFoodInfo.Id.ToString("000"));
}
}
break;
}
}
}
0赞
XNH
11/8/2023
#2
若要访问集合本身,需要使用 PropertyInfo 对象的 GetValue() 方法
private void SelectedFoods()
{
PropertyInfo[] properties = typeof(DailyFoodListViewModel).GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(ObservableCollection<SelectFood>))
{
IEnumerable<SelectFood> collection = (IEnumerable<SelectFood>)property.GetValue(this);
foreach (SelectFood item in collection)
{
if (item.IsChkbxChecked == true)
{
Foodinfo.Foods += item.MyTblFoodInfo.FoodType + string.Format(item.MyTblFoodInfo.Id.ToString("000"));
}
}
break;
}
}
}
评论
foreach (var item in (ObservableCollection<SelectFood>)property.GetValue(model)) { ... }