C# 在c中使用变量访问类属性#
我在c#窗口应用程序中有以下模型类。我有表单控件,我想在表单验证后为模型属性赋值。我有更多的控件,很多控件都是相同的。因此,我不想单独验证每个控件,而是希望循环相同的控件,然后验证for循环C# 在c中使用变量访问类属性#,c#,C#,我在c#窗口应用程序中有以下模型类。我有表单控件,我想在表单验证后为模型属性赋值。我有更多的控件,很多控件都是相同的。因此,我不想单独验证每个控件,而是希望循环相同的控件,然后验证for循环 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TShopLibrary { public c
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TShopLibrary
{
public class CustomerModel
{
public int id { get; set; }
public string Name { get; set; }
public string Contact1 { get; set; }
public string Contact2 { get; set; }
public string RefContact { get; set; }
public decimal ShirtLength { get; set; }
public List<ShirtBottomTypeModel> ShirtBottomType { get; set; } = new List<ShirtBottomTypeModel>();
public decimal Sleeve { get; set; }
public decimal Shoulder { get; set; }
public decimal Chest { get; set; }
public decimal ShirtBottom { get; set; }
public decimal ShalwarLength { get; set; }
public decimal ShalwarWidth { get; set; }
public decimal ShalwarBottom { get; set; }
public decimal ShalwarBottomOpening { get; set; }
public List<NeckTypeModel> NeckType { get; set; } = new List<NeckTypeModel>();
public decimal ChestPlateLength { get; set; }
public decimal ChestPlateWidth { get; set; }
public decimal NeckWidth { get; set; }
public decimal NeckHeight { get; set; }
public decimal Pocket { get; set; }
public List<SewingTypeModel> SewingType { get; set; } = new List<SewingTypeModel>();
public decimal Comments { get; set; }
public decimal CreatedDate { get; set; }
public decimal UpdtedDate { get; set; }
public CustomerModel()
{
}
}
}
在我的ValidateForm()中,我需要如下内容
foreach (Control ctrl in Controls.OfType<TextBox>())
{
if(ctrl.Text!="")
{
customermodel[ctrl.Name] = ctrl.text;
}
}
foreach(Controls.OfType()中的控件ctrl)
{
如果(ctrl.Text!=“”)
{
customermodel[ctrl.Name]=ctrl.text;
}
}
总之,一切都是好的。问题就在这里
customermodel[ctrl.Name]=ctrl.text 您可以这样做:
var props = typeof(Control).GetProperties();
foreach (var p in props)
{
var value = p.GetValue(control_instance);
if (p.Name == "Text")
Do stuff....
}
您好,“这篇文章不起作用。”这样的句子通常是问题级联的开始,以找出所有必要的信息,从而清楚地了解您的问题。请为我们节省时间,并详细说明这一事实。实际发生了什么?乍一看:能够在自定义对象上使用
[…]
,如此行所示:customermodel[ctrl.Name]=ctrl.text代码>需要重写索引运算符。因为我在您的CustomerModel
类中没有看到这段代码。这将导致编译错误。可以在您喜爱的搜索引擎中研究此编译错误。最好先检查它是否匹配,然后获取要使用它的实例的值。
var props = typeof(Control).GetProperties();
foreach (var p in props)
{
var value = p.GetValue(control_instance);
if (p.Name == "Text")
Do stuff....
}