C# &引用;标签";列表中的字符串<&燃气轮机;

C# &引用;标签";列表中的字符串<&燃气轮机;,c#,string,list,C#,String,List,我有三种类型的字符串,我需要将它们按特定顺序放入单个列表中。所谓“三种类型”,我的意思是有三种处理字符串的方法。 我想用这样的struct来放入列表: struct Chunk { public char Type; // 'A', 'B' or 'C'. public string Text; } 也许有更好的方法来标记字符串的处理方式?您可以使用。这将为您提供智能感知和错误检查 struct Chunk { public TheType Type; // '

我有三种类型的字符串,我需要将它们按特定顺序放入单个列表中。所谓“三种类型”,我的意思是有三种处理字符串的方法。 我想用这样的
struct
来放入列表:

struct Chunk
{
    public char Type;   // 'A', 'B' or 'C'.
    public string Text;
}
也许有更好的方法来标记字符串的处理方式?

您可以使用。这将为您提供智能感知和错误检查

struct Chunk
{
    public TheType Type;   // 'A', 'B' or 'C'.
    public string Text;
}

enum TheType { A, B, C }

根据您将如何使用这些块,多态性可能是您的朋友。区块的
类型
实际上包含您的“
类型
”信息:

public abstract class Chunk {
   public string Text { get; private set; }

   protected Chunk(string text) {
      Text = text;
   }
}

public class ATypeChunk : Chunk {
   public ATypeChunk(string text) : base(text) { }
}

public class BTypeChunk : Chunk {
   public BTypeChunk(string text) : base(text) { }
}
从某个源创建块:

public IEnumerable<Chunk> GetChunks(string dataToBeParsed) {
   while ( /* data to be parsed */ ) {

      // Determine chunk type

      switch ( /* some indicator of chunk type */ ) {
         case 'A':
            yield return new ATypeChunk(chunkText);
         case 'B':
            yield return new BTypeChunk(chunkText);
      }     
   }
}
*好的,你可以,但可能有更好的方法。例如,这里有一个常见用法

这是我在试图将我的脑袋绕到这一切的时候问的一个问题:


注意数组。排序方法:)

我不会在这里使用
struct
——类应该可以。有一些预构建的数据类型可用于标记:

  • KeyValuePair
    ,字典迭代器中使用的类型,允许您将值与键配对,而无需定义新类型
  • 从.NET 4.0开始,您可以使用
    Tuple
    对任意类型的项进行配对

我建议为类型定义一个
enum
,而不是使用
char
:这会使程序具有更好的可读性。

FWIW我没有投反对票,但这并不能回答问题。
public UseChunk(Chunk chunk) {
   if (chunk is ATypeChunk)
      // Do something A specific
   else if (chunk is BTypeChunk)
      // Do something B specific
}