这是一个错误还是我在解释'??' - 操作员错误?查看下面的获取属性和评论。

我正在使用c#.net 3.5

    private List<MyType> _myTypeList;

    private List<MyType> MyTypeList
    {
        get
        {
            //The two code lines below should each behave as the three under, but they don't?
            //The ones uncommented are working, the commented result in my list always returning empty (newly created I suppose).

            //return _myTypeList ?? new List<MyType>();
            //return _myTypeList == null ? new List<MyType>() : _myTypeList;

            if (_myTypeList == null)
                _myTypeList = new List<MyType>();
            return _myTypeList;
        }
    }

编辑:对所有刚从问问题的人看来的人,对不起,其中有一些错误会使所有人感到困惑。

感谢所有的出色反馈!我现在理解了我犯的错误。 谢谢!

有帮助吗?

解决方案

这线:

return _myTypeList == null ? new List<MyType>() : _myTypeList;

等同于:

    if (_myTypeList == null)
        return new List<MyType>();
    return _myTypeList;

不:

    if (_myTypeList == null)
        _myTypeList = new List<MyType>();
    return _myTypeList;

带有的版本 ??, ,您稍后添加,这是如此不可读取,以至于我不会分析它。让我们开始 ? 首先。

其他提示

如果您必须使用 ?? 使用它

_myTypeList = _myTypeList ??  new List<MyType>();
return  _myTypeList;

但是一个简单的话也很好

当您使用语法时

return _myTypeList == null ? new List<MyType>() : _myTypeList;

如果_ mytypelist为null,则返回一个新的mytype type list()的mytype列表。 _ mytypelist仍然保持无效。您不初始化它。

而在第二种情况下,您实际上是初始化_myTypelist,然后将其返回。

版本A:

return _myTypeList ?? (_myTypeList = new List<MyType>()); 

版本B:

return _myTypeList == null ? new List<MyType>() : _myTypeList; 

版本C:

if (_myTypeList == null) 
    _myTypeList = new List<MyType>(); 
return _myTypeList; 

A和C应该行为相同。 b不应该 - 它没有设置 _myTypeList 到一个新列表,它只返回一个。您可以使用在版本A中使用的相同语法使其等效:

return _myTypeList == null ? _myTypeList = new List<MyType>() : _myTypeList; 

?? 操作员的意思是:如果左手操作数不是 null, ,操作的结果是左手操作数。否则,操作的结果是右手操作数。 IE:

foo = bar ?? frob

然后 foo = bar 如果 bar != null, , 否则, foo = frob.

您要演示的代码,不使用?操作员(Cocece Operator)。相反,您正在使用三元操作员。

尝试

return _myTypeList ?? ( _myTypeList = new List<MyType>() );

反而。

看一下这个:

        static void Main( string[] args )
        {
            var x = GetList ();

            if( _theList == null )
            {
                Console.WriteLine ("_theList is null");
            }
            else
            {
                Console.WriteLine ("_theList has been initialized.");
            }
            Console.ReadLine ();
        }

        private static List<int> _theList;

        public static List<int> GetList()
        {
            return _theList ?? ( _theList = new List<int> () );
        }

上面的代码将输出“ _thelist已被初始化”。

您的评论行:

//return _myTypeList == null ? new List<MyType>() : _myTypeList;

永远不会按照您的期望工作,因为您不会(懒惰)在任何地方初始化_mytypelist。
_myTypeList == null将始终评估为true,因为_ mytypelist从未初始化,因此您始终返回一个新的列表实例。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top