现在,我正在尝试重构我的c#代码,我需要一些建议:)很抱歉,如果有任何语法/拼写错误,英语不是我的母语
在我的代码中,我多次更改TableCells、TextBox、Label等的文本。。。用一个小测试(在DateTime上总是相同的测试)。因此,我发现将所有这些重构为一个通用方法会很好。但我有一些问题。
这是我的方法代码:
private void testDateTimeNonValideIntoControls<T>((DateTime date, ref Control control)
{
string convertedDate = date.ToString("dd/MM/yyyy");
if (typeof(T) == typeof(System.Web.UI.WebControls.Label))
{
if (convertedDate != "01/01/0001")
((Label)control).Text = convertedDate;
else
((Label)control).Text = " --- ";
}
if (typeof(T) == typeof(System.Web.UI.WebControls.TableCell))
{
if (convertedDate != "01/01/0001")
((TableCell)control).Text = convertedDate;
else
((TableCell)control).Text = " --- ";
}
[...]
}
我不习惯泛型方法/类,但我认为那个方法有问题。
尽管如此,当我称之为:
testDateTimeNonValidateIntoControls((DateTime日期,引用控制控件)
testDateTimeNonValideIntoControls<Label>(date1st, ref (Control)LabelValueDatePremContrat);
我在"control"强制转换上有一个错误。"ref或out参数必须是可赋值变量"所以我试着做一些类似的事情
ref (Control)(ref LabelValueDD)
但是没有。
有人能帮我做这件事吗?我希望能够使用通用方法:)!
正如所写的,这并不能充分利用泛型,而且可以在没有泛型的情况下编写,所以类似于:
private void testDateTimeNonValideIntoControls(DateTime date, Control control)
{
string convertedDate = date.ToString("dd/MM/yyyy");
if (string.Equals(convertedDate, "01/01/0001"))
{
convertedDate = " --- ";
}
var lbl = control as Label;
if (lbl != null)
{
lbl.Text = convertedDate;
}
else
{
var td = control as TableCell;
if (td != null)
{
td.Text = convertedDate;
}
// [...]
}
}
将方法头更改为
private void testDateTimeNonValideIntoControls<T>(DateTime date,Control control)
(删除"控制"旁边的参考号)
此外,
我会听从罗兰的回答。我忘了"as"这个词
感谢