C# 如何在函数中将类变量动态定义为参数

C# 如何在函数中将类变量动态定义为参数,c#,.net,winforms,function,class,C#,.net,Winforms,Function,Class,我不能为我的问题找到正确的标题,因为我的问题有点复杂。让我先解释一下我的代码 public class Route { public String Id {get;set;} public string routeNo {get;set;} public string source {get;set;} } 用于数据交换的类。我有赢的形式,其中有所有领域的路线类。对于每个变量,我都有标签、文本框、ErrorLabel。我有一个在休假时调用的函数 public parti

我不能为我的问题找到正确的标题,因为我的问题有点复杂。让我先解释一下我的代码

public class Route
{
   public String Id {get;set;}

   public string routeNo {get;set;}

   public string source {get;set;}
}
用于数据交换的类。我有赢的形式,其中有所有领域的路线类。对于每个变量,我都有
标签、文本框、ErrorLabel
。我有一个在休假时调用的函数

 public partial class AddRoute : Form
    {
        Route r=null;
        public AddRoute()
        {
            InitializeComponent();
            r = new Route();
        }

       private void textBoxSource_Leave(object sender, EventArgs e)
       {
         showErrorLabel(labelSourceError, textBoxSource.Text, r.source);   
       }
    }
已在表单构造函数中初始化路由类的对象r

 private void showErrorLabelString(Label l, string textboxtext, Route.source a)
 {
     if ((string.IsNullOrEmpty(s)) || (s.Length > 50))
     {
         isError = isError && false;
         l.Text = "Please Enter Data and Should be smaller than 50 Character";
         l.Visible = true;
    }
    else
    {
        a = textboxtext;
    }
}
现在是解释问题的时候了。我想为所有textbox leave事件使用公共函数
batherRorLabelString(标签l,字符串textboxtext,Route.source a
),该函数将检查数据是否正确,如果是,则将其分配给类变量。但问题是
中的
数据类型应该是什么
,以便动态标识类的哪个变量需要赋值。现在你必须想想你为什么要这样做,为什么

  • 提高绩效
  • 在休假事件中验证所有数据,并将其分配到类对象中,该类对象将保存少量的
    ,以检查是否验证了数据
  • 要减少按钮单击事件上的负载
  • 最后是尝试不同的东西
我想你需要一份工作

它的工作原理类似于函数指针,函数接受它作为参数,当您调用它时,您会将要执行的函数传递给它

private void textBoxSource_Leave(object sender, EventArgs e)
{
    showErrorLabel(labelSourceError, textBoxSource.Text, val => r.source = val);
}

private void showErrorLabelString(Label l, string textboxtext, Action<string> update)
{
    if ((string.IsNullOrEmpty(s)) || (s.Length > 50))
    {
        isError = isError && false;
        l.Text = "Please Enter Data and Should be smaller than 50 Character";
        l.Visible = true;
    }
    else
    {
        update(textboxtext);
    }
}
private void textBoxSource\u Leave(对象发送方,事件参数e)
{
淋浴标签(labelSourceError,textBoxSource.Text,val=>r.source=val);
}
私有标签字符串(标签l、字符串textboxtext、操作更新)
{
if((string.IsNullOrEmpty(s))| |(s.Length>50))
{
isError=isError&&false;
l、 Text=“请输入数据,且应小于50个字符”;
l、 可见=真实;
}
其他的
{
更新(textboxtext);
}
}

通过这种方式,淋浴RorLabelString与您要更新的对象类型保持完全独立。

在此示例中,我的businessObject仅为r。现在您添加了一些代码,我稍微更改了示例并重命名了一些变量。