且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何对数组元素使用减法运算符

更新时间:2023-02-05 13:41:03

我认为你需要停下来,退后一步思考你在做什么 - 因为你现在似乎在随意尝试,希望他们能够工作。



但myArr2包含数字数据。它包含双倍值。

不,它没有' t:

I think you need to stop, take a step back and think about what you are doing - because you currently appear to be trying things at random and hoping they will work.

"But myArr2 contains numerical data. It contains double values."
No, it doesn't:
String[] myArr2 = (String[])arrList2.ToArray(typeof(string));



将MyArr2声明为一个字符串数组 - 你输入的值是双值的字符串表示并不重要:C#是强类型的不会为你转换它们。如果你说我想要字符串,那么你得到的字符串,以及它们保留的字符串,直到你明确地将它们改为其他东西 - 你不能用演员表做,你需要将它们解析为数字并以这种方式转换它们。



你不能减去字符串,因为它没有意义:Hello减去Goodbye的价值是多少?



当你 知道 它们是数值时,这听起来像是一个愚蠢的限制,但实际上它是C#弱于打字的优势之一像VB这样的语言:你掌控着你得到了你所要求的东西,而不是编译器认为你可能想要得到的东西。这意味着不小心试图从Hello中减去Goodbye的问题总是在编译时遇到时间,而不是在运行时 - 并且更容易找到和修复。



现在,尝试一些不同的东西:而不是有两个不同的数组(或列表) ,或 - Gawd帮助我们 - ArrayLists)并保持全部step,为什么不正确地看它,并构造一个类,它将字符串CANBusYellow和double值放在一起,并且只有一个类的List,这意味着字符串和它的值保持在一起,所以如果你需要的话一,你有另一个吗?这真的,真的,不难做到......


That declares MyArr2 as an array of strings - it doesn't matter that teh values you put into it are the string representation of double values: C# is strongly typed and will not convert them for you. If you say "I want strings" then strings you get, and strings they stay until you explicitly change them to something else - which you can't do with a cast, you need to parse them as a number and convert them that way.

And you can't subtract strings, because it makes no sense: what is teh value of "Hello" minus "Goodbye"?

This may sound like a stupid restriction when you know they are numeric values, but it's actually one of the strengths of C# over weakly typed languages like VB: you are in control and you get what you ask for, not what the compiler thinks you might be trying to get./ Which means that problems like accidentally trying to subtract "Goodbye" from "Hello" always get caught at compile time, not at run time - and are a lot easier to find and fix.

Now, try something a bit different: instead of having two different arrays (or Lists, or - Gawd help us - ArrayLists) and keeping then all in step, why not look at doing it properly, and constructing a class which holds the string "CANBusYellow" and the double value together and have a single List of the class which means that the string and it's value are kept together, so if you need one, you have the other? It's really, really, not difficult to do...