[英]Getting 'basic' datatype rather than weird nullable one, via reflection in c#
[英]C# reflection datatype
我想優化下面的代碼,唯一的區別是數據類型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;
}
}
減少重復代碼的一種方法是使用text
變量,然后將其分配給control.Text
。
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;
}
如果您使用的是C#7或更高版本,則可以使用模式匹配:
if (control is RadioButton rb) {
rb.Text = text;
} else if (control is Label lbl) {
lbl.Text = text;
} else if (control is Button btn) {
btn.Text = text;
}
您可以使用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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.