开发者

How do I create a static array containing my custom class?

I have a method that returns an array of custom class objects that are created by parsing a text file. At the moment every time I use it I am rereading the file which isn't very efficient.

What I wat to do is create an array contain开发者_StackOverflow中文版ing the objects when the page loads and store them in an array which can then be used later.

The method is:

public Album[] readArray(string sTextFilePath)
    {
        string[] allLines = File.ReadAllLines(Server.MapPath(sTextFilePath));
        Album[] Albums = new Album[allLines.Length];
        for (int i = 0; i < allLines.Length; i++)
        {
            string[] lineSplit = allLines[i].Split(',');
            Albums[i] = new Album();
            Albums[i].ID = Convert.ToInt32(lineSplit[0]);
            Albums[i].title = lineSplit[1];
            Albums[i].keyName = lineSplit[2];
        }

        return Albums;
    }

and the class is simple, just:

    public class Album
{
    public int ID { get; set; }
    public string title { get; set; }
    public string keyName { get; set; }
}

I thought I could create the static object using something like:

static Album myAlbums[] = readArray("Albums.txt");

but I am getting the following error:

A field initializer cannot reference the nonstatic field, method, or property 'B2M._Default.readArray(string)'

I am new to C# so this is probably something dumb. (Feel free to poke fun in my general direction if this is the case!)

Thanks in advance for any assistance,

Ben


"An error" isn't very descriptive. When you're posting a question and you're getting an error, please state what that error is.

In this case the problem is that you're trying to call an instance method (readArray) from a static context, without specifying an instance.

The method doesn't appear to require any instance data, so you should be able to just make the method static and all will be well.

I'd encourage you to read up on .NET naming conventions, btw. You might also want to think about using a List<T> instead of an array. When you feel more confident, you could also make this code simpler using LINQ - but I'd wait until you're more familiar with C# first.


Except for the static context, shouldn't it be:

static Album[] myAlbums = readArray("Albums.txt");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜