吸气属性没有人叫它运行 [英] Getter property is run without anyone calling it

查看:107
本文介绍了吸气属性没有人叫它运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.NET 3.5的工作。
我有一个A级具有堆栈和一个getter属性,它被调用时,将删除在栈中的第一项,并检索下一个。



初始化类后,我看到的getter作品,未经被调用,并在栈中删除顶部的项目,从而使我坏的结果。在吸气的断点并没有表现出任何人穿过它。



在我的属性更改为一个函数,堆栈返回ok了。

$ B $ ; b

我会很高兴,如果有人能解释这是为什么。



下面是简化类:

 大众A级
{
私人堆叠式和LT;字符串>网址;

公开发行A(字符串名称,String []数组),
{
的url =新的堆栈<串GT;();
的foreach(字符串s数组)
{
Urls.Push(S);
}
}

公共字符串地址
{
{返回Urls.Peek(); }
}
公共字符串NextUrl
{
获得{
如果(Urls.Count→1)
{Urls.Pop(); }
返回Urls.Peek();
};
}
}


解决方案

首先,使得属性访问器更改状态通常是一个坏主意。它应该做的最多的就是懒洋洋地初始化的东西 - 或者可能给挥发性值(如 DateTime.Now 一样)



其次,你可能会看到这一点,如果你在调试器下运行 - 当你执行代码,它访问性能。这可能会解释为什么断点没有被击中了。


I'm working in .net 3.5. I have a class "A" which has a stack and a getter property which, when called, removes the first item in the stack and retrieves the next one.

After initializing the class, I saw that the getter works without being called, and removes the top item in the stack, thus giving me bad results. A breakpoint in the getter did not show anyone passing through it.

When I change the property to a function, the stack is returned ok.

I'd be happy if someone could explain why is that.

Here is the simplified class:

 public class A
    {
        private Stack<string> Urls;

        public A(string title, string[] array)
        {
            Urls = new Stack<string>();
            foreach (string s in array)
            {
                Urls.Push(s);
            }
        }

        public string Url
        {
            get { return Urls.Peek(); }
        }
        public string NextUrl
        {
            get{
            if (Urls.Count > 1)
                { Urls.Pop(); } 
            return Urls.Peek(); 
            };
        }            
    }

解决方案

Firstly, making a property accessor change the state is generally a bad idea. The most it should do is lazily initialize something - or possibly give a volatile value (like DateTime.Now does).

Secondly, you're probably seeing this if you're running under the debugger - it accesses properties while you're stepping through code. That would probably explain why the breakpoint wasn't being hit, too.

这篇关于吸气属性没有人叫它运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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