在向List添加struct的foreach循环中的异常

时间:2013-01-22 13:18:41

标签: c#

大家好我有这样的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        struct Proxy
        {
            public static List<string> proxyList;
            public static string type;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "Choose file with proxy";
            openFileDialog1.InitialDirectory = System.Environment.CurrentDirectory;
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            if (checkBox1.Checked)
                Proxy.type = "socks5";
            else
                Proxy.type = "http";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach (string prox in File.ReadAllLines(openFileDialog1.FileName))
                {
                    if (prox.Contains(":"))
                    {
                        string[] proxy = prox.Split(':');
                        Proxy.proxyList.Add(prox);
                    }
                }
                MessageBox.Show(Proxy.proxyList.Count.ToString());
            }
        }

    }
}

但是当我加载txt文件时:

62.109.28.37:8085
193.0.147.23:8085
193.0.147.90:8085
193.0.147.61:8085
193.0.147.47:8085
193.0.147.93:8085

我收到一个例外:在线Proxy.proxyList.Add(prox);  对象引用未设置为对象的实例。

为什么?= \

2 个答案:

答案 0 :(得分:6)

您需要在使用之前构建列表,例如,在foreach循环之前:

Proxy.proxyList = new List<string>();

或者您可以在结构定义本身中执行此操作:

    struct Proxy
    {
        public static List<string> proxyList = new List<string>();
        public static string type;
    }

答案 1 :(得分:6)

因为proxyListnull。改变

public static List<string> proxyList;

public static List<string> proxyList = new List<string>();