【发布时间】:2014-10-22 14:25:34
【问题描述】:
我有三种可能的输入类别,分别是人名、公司名或地址。
忽略我的占位符和自定义方法,这里有两个:
protected void nameSearch_Click(object sender, EventArgs e)
{
if (offRadio.Checked == false && comRadio.Checked == false)
{
errorAlert("Please specify the search type");
}
else
{
strValidator(nameBox.Text);// This is the function I need to change.
//In it's current condition, it will only validate against
// general properties, however to do more in depth
// validation, the validation method needs to be dependant
// on the type of input
if (nameBox.Text != string.Empty)
{
if (offRadio.Checked == true)
//This is an input of the person name category
{
logic.createQuery(fnms(nameBox.Text),
"personName", lnms(nameBox.Text));
}
else if (comRadio.Checked == true)
//And this is of the Company name category
{
logic.createQuery(nameBox.Text, "companyName");
}
}
else
{
errorAlert("Please enter a search parameter");
}
}
}
这里的目标是分析来自nameBox.Text 的输入,并根据反注入协议对其进行审查。理想情况下,我希望使用一种方法来执行此操作,并且该方法会根据输入来自人名 (offRadio.Checked = true) 还是公司名称而有所不同 (comRadio.Checked = true)。我可以有两种方法(或者甚至一种,基于条件),但这会导致nameSearch_Click() 成为嵌套语句的相对泥潭,我想避免这种情况。
根据我的一些研究,执行此操作的方法是使用委托 void,但是我不知道如何实现这一点。我的验证方法是代表吗?或者我必须创建一个新的委托方法并将我的 Click 事件的内容移动到它吗?
另外,如何添加逻辑来决定输入类别是什么?
【问题讨论】:
-
为什么是
delegate?你不能用一些参数(单选按钮的值或基于它们的值的enum值)调用验证类的一些方法吗?例如,Validator.CheckUrl(textBoxUrl.Text, Validator.Mode.TrimSpaces); -
@Sinatr 我们的想法是让代码尽可能小,但您可能是对的,因为您的建议可能是我的...“最安全”的选项。
-
请显示大代码,我们会看到。
标签: c# validation webforms delegates