C# 字符串。替换为空值
我有一个Replace方法,它可以接受Xml节点名作为变量,Replace将在 Xml中的每一行在计算表达式之前获取节点的值。所以如果有的话 节点不存在替换将在null上计算 鉴于此情况,以下代码是否合理C# 字符串。替换为空值,c#,C#,我有一个Replace方法,它可以接受Xml节点名作为变量,Replace将在 Xml中的每一行在计算表达式之前获取节点的值。所以如果有的话 节点不存在替换将在null上计算 鉴于此情况,以下代码是否合理 <chocolates> <chocolate> <name>Mars Bar</name> </chocolate> <chocolate> <name>
<chocolates>
<chocolate>
<name>Mars Bar</name>
</chocolate>
<chocolate>
<name>Bounty</name>
<type>Coconut</type>
</chocolate>
</chocolates>
Replace(type, 'C', 'c')
public string Replace(string a, string b, string c)
{
if (a == null) return null;
if (b == null || c == null) return a;
return a.Replace(b, c);
}
火星酒吧
赏金
椰子
替换(类型“C”、“C”)
公共字符串替换(字符串a、字符串b、字符串c)
{
如果(a==null)返回null;
如果(b==null | | c==null)返回a;
返回a.替换(b,c);
}
代码可以简化:
甚至在trenary操作员的帮助下:
public string Replace(string a, string b, string c)
{
return ((a == null) || (b == null) || (c == null)) ? a : a.Replace(b, c);
}
您应该使用字符串
,例如“c”
,“c”
而不是字符
,“c”
待命:
// All three arguments should be strings
String type = ...
...
Replace(type, "C", "c");
也许您应该通过以下方式调用函数:
Replace(type,"C","C");
(当然,“type”也需要是字符串值)
或者尝试将字符串与null进行比较:
if(a.Equals(null)) return null;
我认为扩展方法看起来会更整洁
public static class MyTestClass
{
public static string MyReplace(this string stringToSearch, string find, string replaceWith)
{
if(stringToSearch == null) return null;
if(string.IsNullOrEmpty(find) || replaceWith == null) return stringToSearch;
return stringToSearch.Replace(find, replaceWith);
}
}
那你就可以打电话了
type.MyReplace('C','c');
编辑:
添加了扩展类的完整代码,并添加了isNullOrEmpty,而不是对“find”进行空检查,因为您不想将空字符串传递给Replace调用您还需要检查b是否为空。否则将发生参数异常
Console.WriteLine(Replace("dsfa", "", ""));
// Define other methods and classes here
public string Replace(string a, string b, string c)
{
if (a == null) return null;
if (String.IsNullOrEmpty(b) || c == null) return a;
return a.Replace(b, c);
}
如果给参数起更好的名字,就更容易看到发生了什么
Console.WriteLine(Replace("dsfa", "", ""));
// Define other methods and classes here
public string Replace(string a, string b, string c)
{
if (a == null) return null;
if (String.IsNullOrEmpty(b) || c == null) return a;
return a.Replace(b, c);
}