将自定义类实例化为数组元素时出现问题 [英] Problem instantiating custom class as array element

查看:85
本文介绍了将自定义类实例化为数组元素时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I've been working on an app to manage my iTunes collection, and have run into a bit of a snag. I've created two classes:

Column – Describes a column of information in the iTunes database
Track – Contains an array of Columns

When I instantiate a new Track object and attempt to build the array of Columns, each "new Column" statement overwrites the value of the previous array element.

I'm sure I'm missing something obvious – any ideas?





// this statement...
Track t = new Track();
// produces this output:
// array element 0 = Name
// array element 0 = Artist
// array element 1 = Artist

// Begin Column class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestBed
{
    public class Column
    {
        private static string _name;
        private static string _datatype = "string";
        private static Int16 _length = 0;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        public string DataType
        {
            get { return _datatype; }
            set { _datatype = value; }
        }
        public Int16 Length
        {
            get { return _length; }
            set { _length = value; }
        }
        public Column(string name, string datatype, Int16 length)
        {

            _name = name;
            _datatype = datatype;

            if (datatype == "string" && length > 0)
            {_length = length; }
            else
            {_length = 0;}
        }

    }
}
// Begin Track class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestBed
{
    public class Track
    {
        private static Column[] _trackcolumns = new Column[2];
        public static Column[] TrackColumns
        {
            get {return _trackcolumns;}
            set { _trackcolumns = value; }
        }
        public Track()
        {

            _trackcolumns[0] = new Column("Name", "string", 30);
            Console.WriteLine("array element 0 = {0}",_trackcolumns[0].Name);

            _trackcolumns[1] = new Column("Artist", "string", 30);
            Console.WriteLine("array element 0 = {0}", _trackcolumns[0].Name);
            Console.WriteLine("array element 1 = {0}", _trackcolumns[1].Name);

        }
    }

推荐答案

static成员变量,为什么哦,上帝告诉我为什么?

问候,

Manfred
static member variables, why oh Lord tell me why?

Regards,

Manfred


这将解释为什么您的静态变量给您带来问题:

已解密的静态关键字 [
This will explain why your static variables are giving you problems:

Static Keyword Demystified[^]


这篇关于将自定义类实例化为数组元素时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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