c# - 将结构添加到列表的 foreach 循环中的异常

标签 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); 对象引用未设置到对象的实例。

为什么?=\

最佳答案

因为 proxyListnull。改变

public static List<string> proxyList;

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

关于c# - 将结构添加到列表的 foreach 循环中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459497/

相关文章:

c# - VS 2008 中的 Web 部署项目工具

c# - 如何用空字符串替换出现的 "-"?

c# - 序列化列表<string>时如何选择内部xml标签?

c# - XmlDocument.Load 替换 ">"

c# - 在 C# 中针对没有 Skip 的 DocumentDB 进行分页

c# - 将方法名称和参数动态传递给thread.Start

C# 9 记录有 ToString() 的 { propertyName=value } 输出,如何从中返回记录类型?

c# - 是否可以在 XAML 中为条目将键盘设置为 "Sentence Capitalisation"?

c# - 来自字符串的新 DateTimeOffset

c# - 告诉 Swashbuckle 只查找具有 ApiControllerAttribute 的 Controller