C#公共变量在类内部可写,但在类外部只读 [英] C# public variable as writeable inside the class but readonly outside the class

查看:114
本文介绍了C#公共变量在类内部可写,但在类外部只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.Net C#类,需要在其中公开变量。我需要在方法中(而不是在构造函数中)初始化此变量。但是,我不希望该变量可以被其他类修改。

I have a .Net C# class where I need to make a variable public. I need to initialize this variable within a method (not within the constructor). However, I don't want the variable to be modifieable by other classes. Is this possible?

推荐答案

不要使用字段-使用属性:

Don't use a field - use a property:

class Foo
{
    public string Bar { get; private set; }
}

在此示例中, Foo.Bar 到处都是可读的,并且只能由 Foo 本身的成员写。

In this example Foo.Bar is readable everywhere and writable only by members of Foo itself.

该示例使用的是第3版引入的C#功能,称为自动实现的属性。这是语法糖,编译器将其转换为具有如下所示的私有后备字段的常规属性:

As a side note, this example is using a C# feature introduced in version 3 called automatically implemented properties. This is syntactical sugar that the compiler will transform into a regular property that has a private backing field like this:

class Foo
{
    [CompilerGenerated]
    private string <Bar>k__BackingField;

    public string Bar
    {
        [CompilerGenerated]
        get
        {
            return this.<Bar>k__BackingField;
        }
        [CompilerGenerated]
        private set
        {
            this.<Bar>k__BackingField = value;
        }
    }
}

这篇关于C#公共变量在类内部可写,但在类外部只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆