检查var是否为String类型

Bul*_*tov 15 c# asp.net asp.net-mvc c#-4.0

我在C#代码中遇到问题:

我不知道如何实现逻辑 - 通过具有不同数据类型值的Hashtable进行迭代,我想要的模式如下:

if the value in variable is String type
{
 do action1;
}
else 
{
  do action2;
}
Run Code Online (Sandbox Code Playgroud)

有一个包含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;
        }   
    }
Run Code Online (Sandbox Code Playgroud)

可能是我编码错了,请指教!

谢谢!

Lee*_*Lee 39

if(conditions[name] is string)
{
}
else
{
}
Run Code Online (Sandbox Code Playgroud)


Can*_*ide 5

嗯,我不确定您为什么打电话IsValueType,但这应该足够了:

if (conditions[name] is string) 
{
    ///  
}
Run Code Online (Sandbox Code Playgroud)