C#中的不可变类型和属性 [英] Immutable type and property in C#

查看:21
本文介绍了C#中的不可变类型和属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 中的不可变类型和不可变属性是什么意思?能举个简单的例子吗?

What is meant by immutable type and immutable property in C# ? can you give simple example?

推荐答案

不可变类型是一种只能在初始化时设置其属性的类型.一旦创建了对象,就不能再更改任何内容.不可变属性只是只读属性.

An immutable type is a type of which its properties can only be set at initialization. Once an object is created, nothing can be changed anymore. An immutable property is simply a read-only property.

在下面的示例中,ImmutableType 是一种不可变类型,具有一个属性 Test.测试是只读属性.只能在施工时设置.

In the following example, ImmutableType is an immutable type with one property Test. Test is a read-only property. It can only be set at construction.

class ImmutableType
{
    private readonly string _test;
    public string Test
    {
        get { return _test; }
    }

    public ImmutableType(string test)
    {
        _test = test;
    }
}

另见:维基百科文章一些堆栈 关于该主题的溢出问题.

这篇关于C#中的不可变类型和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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