正确曝光名单,其中,T>? [英] Properly exposing a List<T>?

查看:151
本文介绍了正确曝光名单,其中,T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我不应该露出了名单,其中,T> 的属性,但我不知道什么是正确的方法是?举例来说,这样做的:

I know I shouldn't be exposing a List<T> in a property, but I wonder what the proper way to do it is? For example, doing this:

public static class Class1
{
    private readonly static List<string> _list;

    public static IEnumerable<string> List
    {
        get
        {
            return _list;
            //return _list.AsEnumerable<string>(); behaves the same
        }
    }

    static Class1()
    {
        _list = new List<string>();
        _list.Add("One");
        _list.Add("Two");
        _list.Add("Three");
    }
}

将允许手机号码简单地转换回名单,其中,T&GT;

    private void button1_Click(object sender, EventArgs e)
    {
        var test = Class1.List as List<string>;
        test.Add("Four"); // This really modifies Class1._list, which is bad™
    }

所以,如果我想要一个真正不变的名单,其中,T&GT; 将我总是要建立一个新的列表?例如,这似乎工作(投试验后为空):

So if I want a really immutable List<T> would I always have to create a new list? For example, this seems to work (test is null after the cast):

    public static IEnumerable<string> List
    {
        get
        {
            return new ReadOnlyCollection<string>(_list);
        }
    }

不过,我担心如果我的列表每当有人试图访问其克隆的性能开销?

But I'm worried if there is a performance overhead as my list is cloned every time someone tries to access it?

推荐答案

使用 AsReadOnly () - 查看MSDN了解详细信息

这篇关于正确曝光名单,其中,T&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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