1

我知道我缺乏关于类和继承之间关系的基本知识

我发现很难理解一件简单的事情:

给定的DDlTextBox可以从后面的代码访问

int selected = DDLID.SelectedIndex ;

string userInput = TBXID.Text;

现在来自放置在代码后面的类:

public static class ControlsValue
{
   public static int UserSel = DDLID.Selected.index;
   public static string UserText = TBXID.Text;
} 

我试图“排列”我的代码,这样我就可以在其他一些项目中重用它

...所以我已将与该类中的代码相关的所有全局变量移到该类中,而我不能做的是用webControls Values

有什么办法呢?

更新

我能想到的一种方法是通过参数

public static class ControlsValue
{
   public static void getValues(DropDownList DDLID)
   {
        public static int UserSel = DDLID.Selected.index;
   }
   public static string UserText(TextBox TBXID)
   {
      return TBXID.Text;
   }
} 
4

1 回答 1

1

像这样创建一个不同的类

public class ControlValues{

    private int_dropDownIndex;
    public int DropDownIndex{
         get { return _dropDownIndex; }
         set { _dropDownIndex= value; }
    }

    private string _textBoxValue;
    public string TextBoxValue{
         get { return _textBoxValue; }
         set { _textBoxValue= value; }
    }

    public ControlValues(int dropDownIndex, string textBoxValue){
         this._dropDownIndex = dropDownIndex;
         this._textBoxValue = textBoxValue;
    }
}

您可以从后面的代码创建一个实例,如下所示

ControlValues cv= new ControlValues(DDLID.Selected.index, TBXID.Text);

现在您可以访问 DropDown 索引和文本

cv.DropDownIndex;  
cv.TextBoxValue;

Although I provided an answer for this, Please note:

  • Remember the stateless nature of web application and the way you are going to use this.
  • In ASP.NET, it will be inefficient to create an Instance of class to hold values of server control because those controls and their values are directly accessible from the code behind. Using this approach will be an extra overhead.
  • If you are serious about learning re-usability, I would strongly recommend you to learn basics of object oriented programming. Once you have a good grip of OOP, you will see clearly when to apply OOP principles.
于 2012-10-24T21:40:43.850 回答