如何在函数中动态定义类变量作为参数

时间:2014-03-13 14:24:22

标签: c# .net winforms function class

我无法为我的问题找到正确的标题,因为我的问题有点奇怪。我先解释一下我的代码

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

   public string routeNo {get;set;}

   public string source {get;set;}
}

数据交换类。我有获胜形式,其中包含路线类的所有领域。对于每个变量,我有label, TextBox, 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);   
       }
    }

在表单构造函数中初始化的Route类的对象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;
    }
}

现在是解释问题的时候了。我希望所有文本框离开事件的公共函数showErrorLabelString(Label l, string textboxtext, Route.source a)将检查数据是否正确,如果是,则将其分配给类变量。但问题是data type中的showErrorLabelString()应该动态识别我需要为哪个类变量赋值。现在你必须想到你为什么这样做,理由

  • 提高绩效
  • 所有数据都在离开事件中验证,并在类对象中分配,这样可以节省很少if else condition来检查数据是否已经过验证。
  • 减少按钮点击事件的负担。
  • 最后是尝试不同的东西。

1 个答案:

答案 0 :(得分:2)

我认为你需要一个Action delegate

它就像一个函数指针,你的函数接受它作为一个参数,当你调用它时,你传递它想要执行的函数。

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);
    }
}

通过这种方式,showErrorLabelString与您要更新的对象的类型完全无关。