【问题标题】:C# issue adding static member to listC# 将静态成员添加到列表的问题
【发布时间】:2016-03-18 15:47:04
【问题描述】:

我正在尝试在列表框中添加一些对象(抛出绑定列表),但是当我显示列表时,该类的静态成员始终具有相同的显示,即最后一个值。我的列表或类中的其他属性没有问题。

以我的形式:

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
         shape.gsPtAcc = ptdep;

         if (shape is Segment)
         {
             seg = shape as Segment;
             seg.gsScPtAcc = ptarr;
         }

         shape.incremNumber();
         Console.WriteLine(shape.Number);//write the correct value
         shapeList.Add(shape);
         listBox1.DataSource = null;
         listBox1.DataSource = shapeList;
        }
    }

在我的妈妈课上,形状:

namespace MyGraphicComponents
{
    abstract class Shape: IComparable<Shape>, IDrawable, INotifyPropertyChanged, IIsPointIn
    {
        protected MyPoint ptAcc;
        public MyPoint gsPtAcc
        {
            get { return ptAcc; }
            set { ptAcc = value; }
        }

        protected static int compt = 0;

        public int Number
        {
            get { return compt; }
            set { compt = value; }
        }
        public int incremNumber ()
        {
            return ++compt;
        }
    }
}

所以结果,当我添加形状时:

  • 在控制台中: 1 2 3 4 5

  • 但在列表框中: 5 5 5 5 5

【问题讨论】:

    标签: c# list static


    【解决方案1】:

    类的静态成员在该类类的所有实例中将具有相同的值

    在这里阅读更多:https://msdn.microsoft.com/fr-fr/library/98f28cdx.aspx

    替换

      protected static int compt = 0; 
    

    protected int compt = 0;
    

    【讨论】:

    • 好的,谢谢,我通过使用数字作为属性解决了这个问题,通过这种方式,我已经能够保持静态属性,只需要做Number=incremNumber ();
    • @RemiHirtz 为什么需要这个静态属性,它似乎是对静态的误用
    • 这是为了学校,我别无选择:s
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多