"只读"属性访问在C# [英] "Read only" Property Accessor in C#

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

问题描述

我有以下类:

class SampleClass
{
   private ArrayList mMyList;

   SampleClass()
   {
       // Initialize mMyList
   }

   public ArrayList MyList
   {
       get { return mMyList;}
   }
}

我希望用户能够拿到mMyList这就是为什么我接触他们为对象的得到通过属性不过,我不希望变化(即MyList.Add(新的Class());),以使其回到我的课的方式。

I want users to be able to get mMyList which is why i exposed the "get" via a property however i don't want changes they make to the object (ie. MyList.Add(new Class());) to make its way back into my class.

我想我可以返回对象的副本,但是可能会很慢,我正在寻找一种方式,将提供编译时错误通知用户他们不应该期望能够修改从属性返回值。

I guess i can return a copy of the object but that may be slow and i'm looking for a way that will provide a compile-time error informing the user that they shouldn't expect to be able to modify the returned value from the Property.

这可能吗?

推荐答案

通过你相当有限,因为没有在BCL没有只读非泛型集合类的ArrayList。快速和肮脏的解决办法是返回IEnumerable类型的。

With an ArrayList you are fairly limited because there is no readonly non-generic collection class in the BCL. The quick and dirty solution is to return a type of IEnumerable.

   public IEnumerable MyList
   {
       get { return mMyList;}
   }

这实际上不会阻止从铸造到ArrayList的一个人,但它不会默认允许编辑任

This won't actually prevent someone from casting to ArrayList but it won't allow edits by default either

您可以通过调用ArrayList.ReadOnly返回一个有效的只读列表。然而,它的返回类型是一个ArrayList,因此用户仍然能够使用。新增编译,但它会产生一个运行时错误。

You can return an effectively readonly list by calling ArrayList.ReadOnly. However it's return type is an ArrayList so the user would still be able to compile with .Add but it would produce a runtime error.

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

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