C# 检查 var 是否为 String 类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13956244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:13:00  来源:igfitidea点击:

To check if var is String type

c#asp.netasp.net-mvcc#-4.0

提问by Bulat Makhmutov

I have a problem in code in C#:

我在 C# 中的代码有问题:

I don't know how to implement logic - iterating through Hashtable having values of different data types, the schema I want is below:

我不知道如何实现逻辑 - 遍历具有不同数据类型值的 Hashtable,我想要的架构如下:

if the value in variable is String type
{
 do action1;
}
else 
{
  do action2;
}


There is a hashtable containing data of Types - String and Int (combined):

有一个包含类型数据的哈希表 - 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;
        }   
    }

May be I am wrong in coding, please advise!

可能是我编码有误,请指教!

Thanks!

谢谢!

采纳答案by Lee

if(conditions[name] is string)
{
}
else
{
}

回答by Candide

Hmm, I'm not sure why you are calling IsValueType, but this should be sufficient:

嗯,我不确定您为什么要调用IsValueType,但这应该足够了:

if (conditions[name] is string) 
{
    ///  
}

回答by Koko

Approach - 1

方法 - 1

Int32 Val = 0;
if (Int32.TryParse("Your Value", out Val))
{
    //Your Logic for int
}
else
{
    //Your Logic for String
}

Approach - 2 (using Late Binding)

方法 - 2(使用后期绑定)

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
    }
}

回答by New_developer

I had the same issue but I was using textBoxes and needed to validate if the input is alphabets,-, or .

我遇到了同样的问题,但我使用的是文本框,需要验证输入是字母、- 还是 .

I generated a keypress event on my textBox and inserted the following method to check each keypress and give a prompt if its not a valid character:

我在我的文本框上生成了一个按键事件,并插入了以下方法来检查每个按键并在它不是有效字符时给出提示:

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;
    }
}


usage:

用法:

 private void txtCustomerName_KeyPress(object sender, KeyPressEventArgs e)
    {            
       Validator.IsNameString(txtCustomerName, "Customer Name", e);

    }