如何在C#中创建只读对象属性? [英] How to Create a Read-Only Object Property in C#?

查看:87
本文介绍了如何在C#中创建只读对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下所示,用户可以更改只读产品字段/属性:

As can be seen below, the user is able to change the readonly product field/property:

class Program
    {
        static void Main(string[] args)
        {
            var product = Product.Create("Orange");
            var order = Order.Create(product);
            order.Product.Name = "Banana"; // Main method shouldn't be able to change any property of product!
        }
    }

    public class Order
    {
        public Order(Product product)
        {
            this.Product = product;
        }

        public readonly Product Product;

        public static Order Create(Product product)
        {
            return new Order (product);
        }
    }

    public class Product
    {
        private Product(){}

        public string Name { get; set; }

        public static Product Create(string name)
        {
            return new Product { Name = name };
        }
    }

我认为这是非常基本的,但事实并非如此.

I thought it's quite basic but it doesn't seem so.

如何在C#中创建只读对象属性或字段?!

How to Create a Read-Only Object Property or Field in C#?!

谢谢

推荐答案

您需要将产品名称属性设为私有集:

You need to make the Name-property of Product private set:

public class Product
{
    private Product(){}

    public string Name { get; private set; }

    public static Product Create(string name)
    {
        return new Product { Name = name };
    }
}

这篇关于如何在C#中创建只读对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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