简单的方法避免在C#中添加字符串
我有几个字符串变量,有时会带有文本,而有时则有整数。我有一个函数add(),当它们是整数时,我添加了所有变量。问题是,当它们是字符串时,如何避免任何变量?示例:
string a = "2";
string b = "3";
string c = "10";
string d = "jk";
string e = "zu";
string f = "15";
public void Add(){
int total = int.Parse(a) + int.Parse(b) + int.Parse(c) + int.Parse(d) + int.Parse(e) + int.Parse(f);
}
显然,以上代码会失败,因为D和E是字符串,我正在寻找的是避免添加D和E字符串,总计应该为30。我可以检查字符串是整数还是文本,但是如果我正在执行的脚本没有字符串作为数组,将永远使用。 做这件事的正确和简单方法是什么?
I have couple of string variables that sometimes have text and other times have integers in them. I have a function Add() where I add all the variables when they are integers. Problem is how do I avoid any variable when they are string? Example:
string a = "2";
string b = "3";
string c = "10";
string d = "jk";
string e = "zu";
string f = "15";
public void Add(){
int total = int.Parse(a) + int.Parse(b) + int.Parse(c) + int.Parse(d) + int.Parse(e) + int.Parse(f);
}
Obviously the above code will fail because d and e are string, what I am looking for is it should avoid adding d and e strings and the total should be 30. I can check if the string is an integer or a text but that would take forever if the script I am working on does not have strings as an array.
What is the right and easy way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果要使用SPESIFIC变量,则可以
使用更扩展的代码来编码此用例,应该使用Collection
int.tryparse将尝试将字符串转换为int。如果无法转换,变量A将为0为默认值。 0是无效的元素。如果此方法是乘法,则应更改这样的方法。
If you want to use spesific variables, you can code this use case like this
If you want to use more extendible code, you should use collection
int.TryParse will try to convert the string to int. If it cannot convert, variable a will be 0 as default. 0 is ineffective element for addition. If this method is multiplication, you should change the method like this.
您可以使用它来检查字符串是可排除的:
而不是解析每个字符串,您可以将它们添加到数组中并在每个周期中遍历它。
因此,您的代码应该看起来像这样:
当然,您可以将字符串添加到AddStrings参数,因为“参数”关键字
You can use this to check wether a string is parsable:
And instead of parsing each string you can add them to a array and traverse it with a for each cycle.
So your code should look like this:
And of course you can keep adding strings to the AddStrings arguments because of the 'params' key word
尝试使用Linq
tried using LINQ