简体   繁体   English

在C#代码中需要帮助

[英]Need help in c# code

I have a function 我有一个功能

protected void bindCurrencies(DropDownList drp)
    {
        drp.DataSource = dtCurrencies;
        drp.DataTextField = "CurrencyName";
        drp.DataValueField = "CurrencyID";
        drp.DataBind();
        drp.Items.Insert(0, new ListItem("Please Select"));
    }

I am binding a dropdown list using this. 我正在使用此绑定下拉列表。 But sometimes I need to bind a ListBox also. 但是有时候我也需要绑定一个ListBox。 I dont want to write a different function for listbox. 我不想为列表框编写其他函数。 How should I do this. 我应该怎么做。 I think Generics method is to be used here. 我认为泛型方法将在这里使用。 But I dont have any idea about generics. 但是我对泛型一无所知。

Both DropDownList and ListBox inherit from ListControl , so if you change your function to take a ListControl as parameter, it should work well with both types: DropDownListListBox都继承自ListControl ,因此,如果您更改函数以将ListControl作为参数,则它应能同时适用于两种类型:

protected void bindCurrencies(ListControl drp)
{
    drp.DataSource = dtCurrencies;
    // and so on...

Ask for a ListControl instead. 要求提供一个ListControl Both ListBox and DropDownList inherit it, so you can use it to contain both. ListBox和DropDownList都继承它,因此您可以使用它包含两者。

Generics is (in most cases) used if you need a class of something . (在大多数情况下)如果需要一类东西,则使用泛型。 For example, a list of strings would be a List in generics. 例如,字符串列表将是泛型列表。

Pass the parameter as an Object, then simply use the object's: 将参数作为对象传递,然后只需使用对象的:

.Getype()

around a select statement and cast it to that type. 在选择语句周围并将其强制转换为该类型。

Unlike the other solutions of Passing a ListControl, this will allow you to pass other controls types (and expand the logic as required). 与传递ListControl的其他解决方案不同,这将允许您传递其他控件类型(并根据需要扩展逻辑)。

EDIT 1 (in response to Sebastian): 编辑1(响应塞巴斯蒂安):

 private void bindCurrencies(object PControl)
 {
    switch (PControl.GetType.ToString) {
        case "Windows.Forms.ListBox":
            Windows.Forms.ListBox ctrl = (Windows.Forms.ListBox)PControl;
            break;
        //Do Logic'
        case "Windows.Forms.DropDownList":
            break;
            //etc 
            //etc
    }
  }

always remember: KISS (Keep It Simple Stupid) 永远记住: KISS (保持简单愚蠢)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM