简体   繁体   English

检查变量是否包含一些字符串

[英]Check if variable contains some string

I have this piece of code 我有这段代码

 if ( x.str_NombreVariable == "User::v_sRutaArchivo")
                            x.str_ValorVariable += str_Archivo;
                        else if ( x.str_NombreVariable == "User::v_IdBitacoraCarga")
                        x.str_ValorVariable = _Bcarga.IdBitacoraCarga.ToString(); 

as you can see I do some comparissions: x.str_NombreVariable == "User::v_sRutaArchivo" or x.str_NombreVariable == "User::v_IdBitacoraCarga" 如您所见,我做了一些比较: x.str_NombreVariable == "User::v_sRutaArchivo" or x.str_NombreVariable == "User::v_IdBitacoraCarga"

problem is that I have values into x.str_NombreVariable who doesn´t have "User::" and it don´t match with comparission. 问题是我有x.str_NombreVariable值, x.str_NombreVariable他没有"User::"并且它与比较不匹配。 So I try to do something like: 所以我尝试做类似的事情:

"User::"+x.str_NombreVariable == "User::v_sRutaArchivo"

Problem is some x.str_NombreVariable come with "User::" as default so I get: 问题是一些x.str_NombreVariable带有默认的“ User ::”,所以我得到:

User::User::NombreVariable 

and it is wrong I only need User::NombreVariable 这是错误的,我只需要User :: NombreVariable

So in other words: How can I check if x.str_NombreVariable doesnt contains "User::" add it and if it have don´t do anything? 因此,换句话说:我如何检查x.str_NombreVariable不包含“ User ::”添加它,以及是否不执行任何操作? it is possible? 有可能的? Regards 问候

Just check if the string starts with User:: and if it does not add it: 只需检查字符串是否以User ::开头,以及是否不添加即可:

if (!x.str_NombreVariable.StartsWith("User::"))
    x.str_NombreVariable = "User::" + x.str_NombreVariable;

Put this code above yours and you should be good. 将此代码放在您的代码之上,您应该会很好。

Edit: I just add missing ')' 编辑:我只是添加缺少的')'

if ("User::v_sRutaArchivo".Contains(x.str_NombreVariable))

这种情况在任何情况下都适用。

Another solution would be to remove the "User::" part from your variable and the hardcoded string: 另一个解决方案是从变量和硬编码字符串中删除“ User ::”部分:

var nombreVar = x.str_NombreVariable.Replace("User::", "");
if ( nombreVar == "v_sRutaArchivo")
    x.str_ValorVariable += str_Archivo;
else if ( nombreVar == "v_IdBitacoraCarga")
    x.str_ValorVariable = _Bcarga.IdBitacoraCarga.ToString(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM