理解属性 C#

如何解决理解属性 C#

我现在正在学习 C# 课程并学习基础知识。我一直在尝试理解属性以及在 C# 中如何准确地获取和设置工作,但我一直让自己感到困惑。我想我已经开始明白了,但如果有人让我知道我有多么正确/错误,我将不胜感激。

我要发布一个我正在复习的练习,关于一个打印矩形的应用程序。练习的重点实际上是练习接口,但属性是最让我困惑的东西

我在此处获得了 Rectangle 类的代码,并且在一些陈述下添加了注释,说明了我认为此处发生的情况。如果有人有任何建议或指导,将不胜感激

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Interfaces_3
{
    class Rectangle : Scalable,Comparable
    {
        double width,height,scale = 1.0;

        public double Scale
        {
            get { return scale; }
            set { if (value > 0) { scale = value; } }
            /* the Scale property will take the scale field value 
             * will update the scale double in the Scalable interface,* but only if the value given to scale is positive*/
        }

        public double Width
        {
            get { return width * scale; }
            set { width = value; }
            /* using the value supplied by the user later,* width field will be set. this will then be multiplied by the scale 
             * field to get the value of Width property */
        }

        public double Height
        {
            get { return height * scale; }
            set { width = value; }
            /* height * scale will be read,and then the width field will
             * be set to the Height property? I think? */
        }

        public double Area
        {
            get { return Width * Height; }
            /* Width * Height is read 
             * there's no 'set' here because... not sure */
        }

        public Rectangle(double width,double height)
        //constructor
        {
            this.width = width;
            this.height = height;
        }

        public bool IsEqual(Object o)
        {
            if (o is Rectangle)
            {
                if (((Rectangle)o).Area == this.Area)
                /* if the Area of "o" is equal to
                 * the Area of the other specified object*/
                {
                    return true;
                }
            }
            return false;
        }

        public bool IsGreater(Object o)
        {
            if (o is Rectangle)
            {
                if (((Rectangle)o).Area < this.Area)
                /* if the Area of "o" is smaller than  
                 * the Area of the other specified object*/
                {
                    return true;
                }
            }
            return false;
        }

        public bool IsLess(Object o)
        {
            if (o is Rectangle)
            {
                if (((Rectangle)o).Area > this.Area)
                /* if the Area of "o" is larger than  
                 * the Area of the other specified object*/
                {
                    return true;
                }
            }
            return false;
        }

        public override string ToString()
        {
            string returnString = "";

            for (int i = 0; i < Math.Ceiling(this.Height); i++)
                /* while i is smaller than the value of Height,rounded up*/ 
            {
                for (int j = 0; j < Math.Ceiling(this.Width); j++)
                /* while j is smaller than the value of Width,rounded up*/
                {
                    Console.Write("/\\");
                }
                Console.WriteLine();
            }
            return returnString;
        }
    }
}

解决方法

实际上,属性就是常规方法,仅此而已。

例如,让我们以自动属性为例:

public class ExampleClass {
  public int ExampleProperty {get;set;}
}

它会被编译成这样:

public class ExampleClass {
 private int _exampleProperty;
 public int get_ExampleProperty() { return _a; }
 public void set_ExampleProperty(int value) { _a = value; }
}

当你写 Console.WriteLine(exampleClass.ExampleProperty) 时,它的意思是 Console.WriteLine(exampleClass.get_ExampleProperty()),而 exampleClass.ExampleProperty = 2 的意思是 exampleClass.set_ExampleProperty(2)。因此,请像常规方法一样考虑它们。

以及您代码中的示例:

public class Rectangle {
 ...
 public double scale;
 public double Scale
 {
  get { return scale; }
  set { if (value > 0) { scale = value; } }
 }
 ...
}


它会被编译成:

public class Rectangle {
 ...
 public double scale
 public double get_Scale() { return scale; }
 public void set_Scale(double value) {
  if (value > 0) {
    scale = value
  }
 }
 ...
}

用法:

var rectangle = new Rectangle(2,2);
rectangle.Scale = 3; // set_Scale(3) call
Console.WriteLine(rectangle.Scale); // get_Scale() call
,

batangaming 很好地解释了这些属性如何在幕后工作。但我想提供一些关于如何使用属性的额外建议。虽然您可以在属性 setter 或 getter 中做任何事情,但重要的是要考虑用户的期望。例如

myRectangle.Scale = -1;

这将编译并运行得很好,但什么也不做,而且可能是一个错误。所以最好把setter写成

public double Scale
    {
        get { return scale; }
        set { 
             if (value > 0) { scale = value; }
             else{ throw new ArgumentException("Invalid scale value,must be positive");
          }
    }

这将确保发现并处理错误。

以同样的方式运行代码

myRectangle.Width = 10;
Console.WriteLine(myRectangle.Width.ToString());

我希望打印的值是 10,但如果 scale != 1,则情况并非如此。因此,您可能希望将值除以 setter 中的 scale。

您也可以考虑mutability vs immutability。 IE。是否允许对象在创建后更改。我个人的偏好是尽可能使用不可变对象。这有许多优点:

  • 对象默认是线程安全的

  • 类(即引用类型)和结构(即值类型)的行为是相同的

  • 仅在构造函数中需要验证

  • 它使对象发生变化的地方更加清晰。 IE。如果我给一个方法一个不可变的对象,我不必担心该对象是否被该方法修改。

  • 它往往使代码非常紧凑。例如:

    public class MyRectangle 
    {
      public double Width { get; }
      public double Height { get; }
      public double Area => Width * Height;
      public MyRectangle Scale(double scale) => new MyRectangle(Width * scale,Height * scale);
      public MyRectangle(double width,double height) => (Width,Height) = (width,height);
    }
    

我还建议查看 IEqualityComparer<T>IComparer<T>。您定义了一个 IsGreater 类,而不是使用 AreaComparer 方法。这允许您以不同的方式比较对象,即您可以同时拥有 AreaComparerWidthComparer

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res