C# 属性 : why does this work?

标签 c# properties set readonly

也许我在最新版本的 C# 中遗漏了一些东西,但对我来说,这段代码应该不起作用,但它确实起作用了..

public class FileManip {
    public FileManip(string path) {
        appPath = path;
    }

    private string appPath {
        get;
    }
    //...............
}

最佳答案

当一个属性有一个带有实现的get时,你有一个不允许写的属性:

public class FileManip {
    public FileManip(string path) {
        AppPath = path;   // <<===== ERROR
    }
    private string AppPath {
        get { return @"c:\temp\"; }
    }
}

然而,当你有一个 { get; } 没有实现,它是一个所谓的只读属性。它已在 C# 6 中添加。您只能从构造函数写入它。您代码的所有其他部分都以只读方式访问此属性。

关于C# 属性 : why does this work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41047208/

相关文章:

C# 异步等待 : How do i write an async method for my example shown below?

c# - Visual Studio 2010 : How do I create and/or update a specific file within a Project from an Editor Extension?

wpf - 如何在组合框中将项目设置为选中

c# - .NET 中 ActiveX 的替代品

c# - 模拟 NLog 的记录器并读取记录的消息

ios - KVO 和重构

vb.net - "obj.X"VB.net 的术语正确吗?

javascript - 更新 javascript 对象属性?

.net - .NET 2.0 中有集合类型吗?

java - 如何在 Java 中实现集合数据结构?