简体   繁体   English

C# 在运行时决定复杂或标准双精度类型

[英]C# decide between complex or standard double type during runtime

I'm writing a sci-comp application in C# (not to be confused with comp-sci), which should accept user inputs as both real and complex numbers.我正在 C# 中编写一个 sci-comp 应用程序(不要与 comp-sci 混淆),它应该接受用户输入作为实数和复数。 This difference between possible inputs would ideally reflect in many points down the stream - if inputs are simple real numbers, I want all objects created from there onwards as simple doubles;可能输入之间的这种差异理想地反映在 stream 的许多点上 - 如果输入是简单的实数,我希望从那里创建的所有对象都是简单的双精度数; if inputs have complex numbers, all relevant objects necessarily must be of complex numbers.如果输入具有复数,则所有相关对象都必须是复数。 (Their syntax, methods and overloads are identical) (它们的语法、方法和重载是相同的)

Now, the reason why I want to do this is that, although it would be safer to assume all inputs as complex from early on, I can save on memory (and potentially processing time) if I can use double types when appropriate.现在,我想这样做的原因是,尽管从一开始就假设所有输入都是复杂的会更安全,但如果我可以在适当的时候使用双精度类型,我可以节省 memory(以及潜在的处理时间)。 I see that would consume only half the necessary memory, and arithmetic operations are simpler in these cases.我看到这只会消耗必要的 memory 的一半,并且在这些情况下算术运算更简单。

To put this simply, during run-time my code would decide what's more appropriate depending on user input, which is acceptable given that syntax is fully re-usable.简而言之,在运行时,我的代码将根据用户输入决定更合适的内容,鉴于语法是完全可重用的,这是可以接受的。 I will try to outline an example using simple int and double datatypes to make this more clear:我将尝试使用简单的 int 和 double 数据类型来概述一个示例,以使这一点更清楚:

    Console.WriteLine("Enter input: ");
    var input = Console.ReadLine();

    bool hasValuesAfterComma = isInputFractional(input);

    double myVar = Double.Parse(input); // This is executed if hasValuesAfterComma == true,
    int myVar = Int.Parse(input); // Otherwise this is considered. All statements after this line work both with double or int types.

How can I set the appropriate data type during runtime?如何在运行时设置适当的数据类型?

PS I'm using the MathNet.Numerics package and its data types to do Linear Algebra processing. PS 我正在使用 MathNet.Numerics package 及其数据类型进行线性代数处理。

Try dynamic variable:尝试动态变量:

dynamic myVar = hasValuesAfterComma? Double.Parse(input): Int.Parse(input);

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

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