我在C#代码中遇到问题:
我不知道如何实现逻辑 - 迭代Hashtable 拥有不同数据类型的值,我想要的架构如下:
if the value in variable is String type
{
do action1;
}
else
{
do action2;
}
有一个包含Types - String和Int(组合)数据的哈希表:
public string SQLCondGenerator {
get
{
Hashtable conditions = new Hashtable();
//data having String data type
conditions.Add("miap", ViewState["miap_txt"]);
conditions.Add("pocode", ViewState["po_txt "]);
conditions.Add("materialdescription", ViewState["mat_desc_txt"]);
conditions.Add("suppliername", ViewState["supplier_txt"]);
conditions.Add("manufacturername", ViewState["manufacturer_txt"]);
//data having Int32 data type
conditions.Add("spareparts", ViewState["sp_id"]);
conditions.Add("firstfills", ViewState["ff_id"]);
conditions.Add("specialtools", ViewState["st_id"]);
conditions.Add("ps_deleted", ViewState["ps_del_id"]);
conditions.Add("po_manuallyinserted", ViewState["man_ins_id"]);
String SQLCondString = "";
String SQLCondStringConverted = "";
string s = string.Empty;
foreach (string name in conditions.Keys)
{
if (conditions[name] != null)
{
SQLCondString += name+ "=" +conditions[name]+ " and ";
Response.Write(conditions[name].GetType());
bool valtype = conditions[name].GetType().IsValueType;
if (valtype == string)
{
SQLCondString.Substring(0, SQLCondString.Length - 4);
SQLCondString += name + " and like '%" + conditions[name] + "%' and ";
}
}
}
//Response.Write("********************");
SQLCondStringConverted = SQLCondString.Substring(0, SQLCondString.Length - 4);
return SQLCondStringConverted;
}
}
可能是我编码错了,请指教!
谢谢!
答案 0 :(得分:37)
if(conditions[name] is string)
{
}
else
{
}
答案 1 :(得分:5)
嗯,我不确定你为什么打电话给IsValueType
,但这应该足够了:
if (conditions[name] is string)
{
///
}
答案 2 :(得分:0)
Int32 Val = 0;
if (Int32.TryParse("Your Value", out Val))
{
//Your Logic for int
}
else
{
//Your Logic for String
}
Int32 Val = 0;
dynamic conditions = new Hashtable();
conditions.Add("miap", ViewState["miap_txt"]);
conditions.Add("pocode", ViewState["po_txt "]);
foreach (string name in conditions.Keys)
{
if (Int32.TryParse(conditions[name].ToString(), out Val))
{
//Your Logic for int
}
else
{
//Your Logic for String
}
}
答案 3 :(得分:0)
我遇到了同样的问题,但是我使用的是textBoxes,需要验证输入的内容是字母,-还是。
我在textBox上生成了一个按键事件,并插入了以下方法来检查每个按键并在其无效字符时给出提示:
public static class Validator
{
public static bool IsNameString(TextBox tb, string name, KeyPressEventArgs e)
{
bool valid = true;
/* e.KeyChar contains the character that was pressed
e.Handled is a boolean that indicates that handling is done
if a bad character is entered, set e.Handled to true
*/
if (!char.IsLetter(e.KeyChar) && e.KeyChar != ' ' && e.KeyChar != '-' &&
e.KeyChar != '.' && e.KeyChar != (char)Keys.Back)
{
e.Handled = true;
valid = false;
MessageBox.Show(name+ " can only accept letters, space, - and .");
tb.Focus();
}
return valid;
}
}
用法:
private void txtCustomerName_KeyPress(object sender, KeyPressEventArgs e)
{
Validator.IsNameString(txtCustomerName, "Customer Name", e);
}