C# 类、方法或解析配置文件的内容

发布于 2024-11-04 01:50:47 字数 430 浏览 1 评论 0原文

对于面向对象的做事方法不熟悉,只是想知道执行此操作的建议方法是什么。

在我的第一个问题中,我询问了有关解析文本文件的问题,现在有了一些好主意(谢谢大家),我开始编写程序的这一部分。

文本文件有多个部分,需要读入多种数据类型。一切进展顺利,随着文本文件的复杂性不断增加,我正在更改代码以适应。但我最终会得到 30 个左右不同的变量/数组/列表等,至少其中一些需要对程序全局可用。

所以我现在有一段代码,目前是包含“main”的类中的一个方法,并且所有变量都是全局的。 (我知道不太好)。

我在想必须有一种更简洁的方法来做到这一点,我在想使用一个单独的类,创建此类的实例并调用此类中解析文本并填充变量的方法。然后简单地从我需要的任何其他类中调用类变量(任何被视为公共的变量)。

但我知道什么:) 只是寻找一些想法,这样我就不会走得太远而不得不折返。

干杯

New to the object orientated method of doing things and was just wondering what is the suggested method for doing this.

in my first question I asked about parsing a text file, and now with some good ideas (thank you guys) I am starting to write this part of the program.

the text file has multiple sections and multiple data types needed to be read in. This is going fine and as the complexity of the text file grows so the I am changing the code to adapt. But I will end up with 30 or so different variables/arrays/list etc that at least some will need to be global available to the program.

So I now have a chunk of code that at the moment is a method within the class that contains "main", and all the variables are global. (not nice I know).

I was thinking there must be a neater way to do this, I was thinking use a separate class, create an instance of this class and call the method with in this class that parses the text and populates the variables. Then simple call the class variables (any ones deemed to be public)from with in any other class I need to.

But then what do I know :) just looking for some ideas so i don't go to far down the road and have to turn back.

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

无边思念无边月 2024-11-11 01:50:47

你的直觉很好;解析特定类型文本文件的任务应该封装在一个类中,该类给出一些有关从哪里获取数据的信息,并生成表示解析数据的对象图。就输入而言,带有文件名的字符串就可以了;更好的是,传入 Stream 或 StreamReader;然后,同一个解析器可以消化来自文件、内存块或网络传输的信息。

一定要把事情分解成可重复的块;如果文件由许多解析为子对象的相似行组成,请创建一个方法来解析单行并返回子对象。

还要使事情尽可能单一目的;如果您必须处理两种类型的文本文件,请为每种文件类型创建一个类,尽可能使它们实现相同的接口。然后,您可以实现所谓的策略模式,其中一个对象的工作是根据具体情况确定应使用一系列其他类中的哪一个来执行任务。

Your instincts are good; the task of parsing a particular type of text file should be encapsulated in a class that is given some information about where to get the data, and produces an object graph representing the parsed data. As far as the input, a string with the filename is fine; better yet, pass in a Stream or StreamReader; the same parser can then digest the information from a file, memory block or network transmission.

Definitely break things down into repeatable chunks; if a file consists of a lot of similar lines that are parsed into subobjects, create a method to parse a single line and return the subobject.

Also make things as single-purpose as possible; if you have to deal with two types of text files, create one class for each file type, making them implement the same interface if possible. Then, you can implement what's called a Strategy pattern, where one object's job is to determine which of a series of other classes should be used to perform a task depending on the specifics.

白首有我共你 2024-11-11 01:50:47

为了简单起见,我将使用 序列化器 类来执行此操作:

这是示例配置类:

[Serializable]
public class Config
{
    public int ValueOne { get; set; }
    public string ValueTwo { get; set; }
    public int[] LotsOfValues { get; set; }
    public List<FurtherConfig> Other { get; set; }
}

[Serializable]
public class FurtherConfig 
{
    public int Value { get; set; }
}

这是一些示例用法:

var config = new Config
{
    ValueOne = 23,
    ValueTwo = "Second Value",
    LotsOfValues = new[] { 23, 34, 34 },
    Other = new List<FurtherConfig> {
        new FurtherConfig { Value = 567},
        new FurtherConfig { Value = 98 }
    }
};

var serializer = new XmlSerializer(typeof(Config));

//write out to file
using (var fw = File.OpenWrite("config.xml"))
    serializer.Serialize(fw, config);

//read in from file
Config newConfig;
using (var fr = File.OpenRead("config.xml"))
    newConfig = serializer.Deserialize(fr) as Config;

Console.WriteLine(newConfig.Other[1].Value); //prints 98

这是序列化输出:

<?xml version="1.0"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ValueOne>23</ValueOne>
  <ValueTwo>Second Value</ValueTwo>
  <LotsOfValues>
    <int>23</int>
    <int>34</int>
    <int>34</int>
  </LotsOfValues>
  <Other>
    <FurtherConfig>
      <Value>567</Value>
    </FurtherConfig>
    <FurtherConfig>
      <Value>98</Value>
    </FurtherConfig>
  </Other>
</Config>

To keep things simple, I would use the serializer class to do it:

Here is the example Config classes:

[Serializable]
public class Config
{
    public int ValueOne { get; set; }
    public string ValueTwo { get; set; }
    public int[] LotsOfValues { get; set; }
    public List<FurtherConfig> Other { get; set; }
}

[Serializable]
public class FurtherConfig 
{
    public int Value { get; set; }
}

And here is some example usage:

var config = new Config
{
    ValueOne = 23,
    ValueTwo = "Second Value",
    LotsOfValues = new[] { 23, 34, 34 },
    Other = new List<FurtherConfig> {
        new FurtherConfig { Value = 567},
        new FurtherConfig { Value = 98 }
    }
};

var serializer = new XmlSerializer(typeof(Config));

//write out to file
using (var fw = File.OpenWrite("config.xml"))
    serializer.Serialize(fw, config);

//read in from file
Config newConfig;
using (var fr = File.OpenRead("config.xml"))
    newConfig = serializer.Deserialize(fr) as Config;

Console.WriteLine(newConfig.Other[1].Value); //prints 98

This is the serialized output:

<?xml version="1.0"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ValueOne>23</ValueOne>
  <ValueTwo>Second Value</ValueTwo>
  <LotsOfValues>
    <int>23</int>
    <int>34</int>
    <int>34</int>
  </LotsOfValues>
  <Other>
    <FurtherConfig>
      <Value>567</Value>
    </FurtherConfig>
    <FurtherConfig>
      <Value>98</Value>
    </FurtherConfig>
  </Other>
</Config>
谢绝鈎搭 2024-11-11 01:50:47

对于解析,我同意 XML 序列化是一种好方法。

至于如何访问对象中的数据,请考虑 静态类单例模式

For the parsing, I agree that XML serialization is a good way to do things.

As for how to access the data once it's in an object, consider a static class or the Singleton pattern.

起风了 2024-11-11 01:50:47

如果配置文件的格式不是一成不变的,那么我建议使用 System.Xml.XmlSerializer 类将配置文件保存/加载为 xml。

保存起来非常简单..加载将留给您作为练习:

using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.something, FileShare.something))
{
    XmlSerializer serializer = new XmlSerializer(this.getType());
    serializer.serialize(file, this);
}

我可能弄乱了参数的顺序,而且我是一个VB人员,但您明白了。

If the format for the config file is not set in stone, then I would suggest utilizing the System.Xml.XmlSerializer class to save/load your config file as xml.

Pretty simple to save.. load will be left as an excersize for you:

using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.something, FileShare.something))
{
    XmlSerializer serializer = new XmlSerializer(this.getType());
    serializer.serialize(file, this);
}

I may have goofed up the order of the parameters, and I'm a vb guy, but you get the idea.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文