【问题标题】:How to dynamically define class variable as argument in function如何动态地将类变量定义为函数中的参数
【发布时间】:2014-03-13 14:24:22
【问题描述】:

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

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),它将检查数据是否正确,如果是,则将其分配给类变量。但问题是showErrorLabelString() 中的data type 应该是什么来动态识别我需要在哪个类的变量中赋值。现在你一定要想想你为什么会这样,理由

  • 提高性能
  • 所有数据在离开事件时都经过验证,并分配到类对象中,这将节省少量if else condition 以检查数据是否经过验证。
  • 减少按钮点击事件的负载。
  • 最后是尝试不同的东西。

【问题讨论】:

    标签: c# .net winforms function class


    【解决方案1】:

    我认为你需要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 完全独立于您要更新的对象的类型。

    【讨论】:

    • 在此我的 businessObject 仅是 r。
    • 现在你添加了一些代码,我稍微改变了我的示例并重命名了一些变量。
    猜你喜欢
    • 1970-01-01
    • 2015-04-12
    • 2015-10-21
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多