C#作为回报仅得到读的变量;组; [英] C# return a variable as read only from get; set;

查看:127
本文介绍了C#作为回报仅得到读的变量;组;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发誓,我已经看到了这样的一个例子,但已经被google搜索了一下,能不能找到它。

I swear I have seen an example of this but have been googling for a bit and can not find it.

我有了一个引用的类对象并需要有一个GET;方法吧。我的问题是,我不希望任何人能够与它摆弄,即我希望他们能够得到一个只读版本的它,(请注意我需要能够从我的类中改变它)。

I have a class that has a reference to an object and need to have a GET; method for it. My problem is that I do not want anyone to be able to fiddle with it, i.e. I want them to get a read only version of it, (note I need to be able to alter it from within my class).

感谢

推荐答案

没有,有没有这样做的方式。举例来说,如果你返回一个列表<字符串方式> (它不是一成不变的),然后调用者的将会的可以添加的条目

No, there's no way of doing this. For instance, if you return a List<string> (and it's not immutable) then callers will be able to add entries.

正常办法解决这是返回一个不可变的包装,如: ReadOnlyCollection还< T>

The normal way round this is to return an immutable wrapper, e.g. ReadOnlyCollection<T>.

有关其他可变类型,您可能需要返回之前克隆的价值。

For other mutable types, you may need to clone the value before returning it.

请注意,只是返回一个不可变接口视图(如返回的IEnumerable< T> 而不是列表< T> )将不会停止铸造呼叫者。回到可变类型和变异

Note that just returning an immutable interface view (e.g. returning IEnumerable<T> instead of List<T>) won't stop a caller from casting back to the mutable type and mutating.

编辑:注意从别的,除了,这种担心也是为什么不变类型更容易推理的原因之一代码:)

Note that apart from anything else, this kind of concern is one of the reasons why immutable types make it easier to reason about code :)

这篇关于C#作为回报仅得到读的变量;组;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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