C#反射数据类型

时间:2019-05-26 10:08:25

标签: c# optimization reflection

我想优化以下代码,唯一的区别是数据类型RadioButton,Label和Button。在方法之外,我有一个循环遍历aspx-page中的所有控件。

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
...
public partial class MyUserControl : UserControl
...
if (control is RadioButton)
{
    try
    {
        (control as RadioButton).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as RadioButton).Text = "Key not found: " + control.ID;
    }
}
else if (control is Label)
{
    try
    {
        (control as Label).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Label).Text = "Key not found: " + control.ID;
    }
}
else if (control is Button)
{
    try
    {
        (control as Button).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Button).Text = "Key not found: " + control.ID;
    }
}

2 个答案:

答案 0 :(得分:1)

减少重复代码的一种方法是使用int变量,然后将其分配给text

control.Text

如果您使用的是C#7或更高版本,则可以使用模式匹配:

string text = "";
try
{
    text = SPContext.Current.Web.Locale.LCID == 1033 ?
    DataBinder.Eval(keys.en, control.ID).ToString() :
    DataBinder.Eval(keys.sv, control.ID).ToString();
}
catch (Exception)
{
    text = "Key not found: " + control.ID;
}

if (control is RadioButton) {
    (control as RadioButton).Text = text;
} else if (control is Label) {
    (control as Label).Text = text;
} else if (control is Button) {
    (control as Button).Text = text;
}

答案 1 :(得分:1)

您可以使用dynamic来大大简化代码。

由于ID是在基类中定义的,但是Text是在所有具体类中定义的,而不是在基类中定义的。

dynamic myControl = control;
try
{
    myControl.Text = SPContext.Current.Web.Locale.LCID == 1033 ?
    DataBinder.Eval(keys.en, control.ID).ToString() :
    DataBinder.Eval(keys.sv, control.ID).ToString();
}
catch (Exception)
{
    myControl.Text = "Key not found: " + control.ID;
}

您可以在开头添加类型的保护子句:

if (!(control is RadioButton || control is Label || control is Button)) return;