在c#中使用泛型创建树

本文关键字:泛型 创建 | 更新日期: 2023-09-27 17:50:55

我是c#的新手,我刚刚完成了一个huffman tree,现在下一步是使它成为generic,我的意思是这个symbol应该适用于每个data type。因为我是c#初学者,所以我需要一些基本的想法来做到这一点。

我的霍夫曼树由3个类组成。类huffman, node和MyClass(其中包含main函数),其中freqsymbol重复的次数,它们的结构如下所示:

namespace final_version_Csharp
{
    public Class Huffman 
    {
        public classNode 
        {
            public Node next, left, right;
            public int symbol;
            public int freq;
        }
        public Node root;
    }
    public void huffman_node_processing() 
    {
        //done the addition of two minimum freq here
    }
    public void GenerateCode(Node parentNode, string code) 
    {
        //done the encoding work here
    }
    public class MyClass 
    {
        public static void Main(string[] args) 
          {
            Huffman ObjSym = new Huffman(args); //object creation by reading the data fron a file at   sole argument
            //All other methods are here
            ObjSym.huffman_node_processing(); //this for adding the two minimum nodes
            ObjSym.GenerateCode(ObjSym.root, ""); //this for encoding
           }
    }
}

有没有人可以帮助我使这个"符号"工作的所有数据类型,如"短","长"等

在c#中使用泛型创建树

如果我没理解错的话,你基本上会这样做

namespace final_version_Csharp
{
    public Class Huffman<K> where K :  IComparable<K>
    {
        public classNode<K> 
        {
            public Node next, left, right;
            public K symbol;
            public int freq;
        }
        public Node root;
    }
...
    public class MyClass 
    {
        public static void Main(string[] args) 
          {
            Huffman ObjSym = new Huffman<int>(); 
            //All other methods are here
            ObjSym.huffman_node_processing(); //this for adding the two minimum nodes
            ObjSym.GenerateCode(ObjSym.root, ""); //this for encoding
           }
    }
}

您只需使用interface

public interface IMyType
{
    int Symbol { get; set; }
    int Freq { get; set; }
}

则只需将此用于您希望能够通用地使用的所有类。所以

public class ClassA : IMyType
{
    ...
    public int Symbol { get; set; }
    public int Freq { get; set; }
    ...
}
public class ClassB : IMyType
{
    ...
    public int Symbol { get; set; }
    public int Freq { get; set; }
    ...
}

然后你可以在方法中使用这些对象,像这样

void SomeMethod(IMyType o)
{
    o.Symbol = 1;
    o.Freq = 2;
    ...
}
IMyType a = new ClassA();
IMyType b = new ClassB();
SomeMethod(a);
SomeMethod(b);