将值分配给c#中的类实例

发布于 2025-02-03 08:24:03 字数 677 浏览 4 评论 0 原文

我有一个自定义类, complexnumber ,这是您可能期望的一种表示复数数字的方法:

class ComplexNumber
{
    double realPart;
    double imaginaryPart;

    public ComplexNumber(double real, double imaginary)
    {
        realPart = real;
        imaginaryPart = imaginary;
    }
}

这个问题的上下文是,如果要设置默认的C#类,例如double或float对于一个整数的某个值,您可以编写

float f = 2;

我希望能够编写类似的内容,例如,

ComplexNumber c = 2;

这些内容将创建 confecternumber 类的新变量,并使用其 realpart 设置到 2 及其 imagypart 设置为 0 。编写复杂number c =新的复杂number(2,0)更加乏味,我想知道是否有一种方法可以更隐含地创建这些自定义类的实例。

I have a custom class, ComplexNumber, which is as you may expect a way to represent complex numbers:

class ComplexNumber
{
    double realPart;
    double imaginaryPart;

    public ComplexNumber(double real, double imaginary)
    {
        realPart = real;
        imaginaryPart = imaginary;
    }
}

The context of this question is that if you want to set default C# classes such as a double or a float to a certain value which is an integer, you can write

float f = 2;

I want to be able to write something similar like

ComplexNumber c = 2;

which will create a new variable of the ComplexNumber class with its realPart set to 2 and its imaginaryPart set to 0. To write ComplexNumber c = new ComplexNumber(2, 0) is much more tedious, and I am wondering if there is a way to create these instances of a custom class more implicitly like how the default C# classes behave.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅紫色的梦幻 2025-02-10 08:24:03

您可以添加运营商这样的班级:

public static implicit operator ComplexNumber(int i) => new ComplexNumber(i, 0);

这将使您做自己想做的事。

正如您使用 2 作为字面的,这将是 int 在C#中,这依赖于 int 隐式转换为<< int> int代码> double 在“ contuctor”调用复杂number 中。

You can add an implicit (or expicit) operator to your class like so:

public static implicit operator ComplexNumber(int i) => new ComplexNumber(i, 0);

That will allow you do what you want.

As you used 2 as a literal, that will be an int in C#, this then relies on the fact that int is implicitly convertable to double in the contructor call to ComplexNumber.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文