这个问题在评论想出了这个答案.建议不能使用只读属性作为使用字段而不是属性的潜在原因.
例如:
class Rectangle
{
private readonly int _width;
private readonly int _height;
public Rectangle(int width, int height)
{
_width = width;
_height = height;
}
public int Width { get { return _width; } }
public int Height { get { return _height; } }
}
Run Code Online (Sandbox Code Playgroud)
但为什么你不能这样做呢?
public int Width { get; readonly set; }
Run Code Online (Sandbox Code Playgroud)
编辑(澄清):您可以在第一个示例中实现此功能.但是为什么你不能用自动实现的属性速记来做同样的事情呢?它也不会那么混乱,因为你不必直接访问构造函数中的字段; 所有访问都将通过该属性.
编辑(更新):从C#6.0开始,支持只读属性!object MyProp { get; }此属性可以设置为inline(object MyProp { get; } = ...)或构造函数,但不能设置其他地方(就像readonly字段一样).
我正在制作一个小程序,它将抓取我的硬盘并显示在给定驱动器中找到的文件列表.
我的想法是拥有一个基本的File类,并实现从File.cs类继承的Picture.cs,Video.cs和Document.cs类.
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpLibrary_MediaManager
{
public abstract class File
{
public string name;
public string fileType;
public int size;
public DateTime creationDate;
public DateTime modificationDate;
}
}
Run Code Online (Sandbox Code Playgroud)
我应该为每个属性声明这样的简写代码:
public string name { get; set; }
Run Code Online (Sandbox Code Playgroud)
任何指导都会有所帮助.谢谢.:)
编辑:
我的意思是直接替换这一行:
public string name;
Run Code Online (Sandbox Code Playgroud)
用这一行:
public string name { get; set; }
Run Code Online (Sandbox Code Playgroud)