首页 > 解决方案 > 无法在 c# 中将项目添加到列表中,我知道为什么,但无法修复它

问题描述

所以我正在制作一个配置系统,我知道代码很乱,我尝试将一个项目添加到列表中,但它失败了,因为列表似乎是:'null'

我不知何故需要参考:configElements列表,但我不知道怎么做,我翻阅了一些文档和旧的stackoverflow问题,如果这个问题在我之前得到了回答,我非常抱歉,但我找不到问题,也很抱歉我有问题的英语,它不是我的主要语言(?)

这是我到目前为止得到的代码,如果你能解释这个问题,我会非常感谢你。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConfigTest
{
    class Config
    {
        private string configFile;
        private List<string> configElements;

        public Config(string configPath = "unset")
        {
            this.configFile = configPath;
        }

        //Checks if the config file allready exists
        public string makeConfig()
        {
            if (File.Exists(configFile))
            {
                return "Config file allready exists: " + configFile;
            }
            File.Create(configFile);
            return "Made Config file!";
        }

        public string getString(string element)
        {
            string[] configContent = getConfigContentL();
            foreach(string line in configContent)
            {
                if (line.Contains(element))
                {
                    return line.Replace(element + 1, "");
                }
                return "Couldn't find the element: " + element;
            }
            return "Couldn't open config file!";
        }

        private void appendElementToList(string element)
        {
            if (!this.configElements.Contains(element))
            {
                this.configElements.Add(element);
            }
        }

        public void setString(string element, string content)
        {
            string[] configContent = getConfigContentL();
            appendElementToList(element);
            if (configElements.Contains(element))
            {
                foreach(string line in configContent)
                {
                    if (line.Contains(element))
                    {
                        string editElement = getString(element);
                        line.Replace(editElement, content);
                    }
                }
            }
            else
            {
                File.AppendAllText(configFile , element + " " + content);
            }
        }



        public string getConfig()
        {
            return configFile;
        }

        public string getConfigContentF()
        {
            return File.ReadAllText(configFile);
        }

        public string[] getConfigContentL()
        {
            return File.ReadAllLines(configFile);
        }

        public List<string> getElements()
        {
            return configElements;
        }
    }
}

标签: c#

解决方案


推荐阅读