将值分配给c#中的类实例
我有一个自定义类, 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)
更加乏味,我想知道是否有一种方法可以更隐含地创建这些自定义类的实例。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以添加运营商这样的班级:
这将使您做自己想做的事。
正如您使用
2
作为字面的,这将是int
在C#中,这依赖于int
隐式转换为<<int> int代码> double
在“ contuctor”调用复杂number
中。You can add an implicit (or expicit) operator to your class like so:
That will allow you do what you want.
As you used
2
as a literal, that will be anint
in C#, this then relies on the fact thatint
is implicitly convertable todouble
in the contructor call toComplexNumber
.