首页 > 解决方案 > 使用无论值如何总是返回 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。

我没有发现错误,有人可以告诉我如何解决吗?感谢广告提前。

标签: c#classconstructor

解决方案


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

解决此问题的两种方法:

  1. 使用字段支持的属性而不是 auto
     public double Real {
          get { return real; }
          set { real = value;}
     }
  1. 使用 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 无论如何都会在“幕后”创建一个私有字段。


推荐阅读