c# - 使用无论值如何总是返回 0 的类的问题
问题描述
我为复数创建了这个类
using System;
using System.Collections.Generic;
using System.Text;
namespace borrar
{
public class Complejos
{
public Complejos()
{
}
private double real;
private double imaginario;
public Complejos(double Real, double Imaginario)
{
real = Real;
imaginario = Imaginario;
}
public double Real { get; set; }
public double Imaginario { get; set; }
}
}
没有错误消息,但是如果我使用带有两个元素的构造函数,它总是返回 0。例如,如果我写
class Program
{
static void Main(string[] args)
{
Complejos pruebas = new Complejos(1, 1);
Console.WriteLine(pruebaas.Real);
}
}
Visual Studio 返回 0。
我没有发现错误,有人可以告诉我如何解决吗?感谢广告提前。
解决方案
private double real;
private double imaginario;
public Complejos(double Real, double Imaginario)
{
real = Real; // <= this sets the private var "real" to the value of the _param_ "Real".
imaginario = Imaginario;
}
public double Real { get; set; } // <= This is an autoproperty that has
// NOTHING TO DO with "real"
// and is initialized with default(double), which is 0.0
public double Imaginario { get; set; }
因此,由于字段real
和属性没有任何关系,当您像示例中那样进行Real
读取访问时,您将获得双重属性的默认值。Real
解决此问题的两种方法:
- 使用字段支持的属性而不是 auto
public double Real {
get { return real; }
set { real = value;}
}
- 使用 CTOR 中的自动属性并删除私有字段。
public Complejos(double Real, double Imaginario)
{
this.Real = Real; // <= this sets the property "Real" to the value of the _param_ "Real".
this.Imaginario = Imaginario;
}
我会选择选项 1。只有当我有充分的理由这样做时。基本上,AutoProperty 无论如何都会在“幕后”创建一个私有字段。
推荐阅读
- css - 当我点击链接时蓝色
- pine-script - 简单的 Pine 脚本代码来绘制两个股票的一对价格(包括代码)
- c++ - 在这种情况下如何初始化 std::vector ?
- laravel - 在开发的早期阶段是否有替代迁移工作流程。拉拉维尔
- unity3d - 在 Unity 中使用 sprite 遮罩 3D 对象
- arrays - 将数组分配给数组
- javascript - 一键实现两个动作 laravel
- python - Matplotlib 极坐标散点图不显示所有点
- sql - 在 SQL Server 中获取 0.00 十进制值
- wordpress - 如何在 Wordpress 中设置现有产品属性的值?