0

我是新来的c#我刚刚完成了一个huffman tree,现在下一步就是让它generic我的意思是这个symbol应该为每个data type工作。由于我是c#初学者,我需要一些基本的想法来做到这一点。在c#中使用泛型创建树#

我的霍夫曼树由3个类组成。类霍夫曼,节点和MyClass的(其中包含的主要功能),其中freq是时代的symbol重复下面给出它们的结构数量:

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 
      } 
    } 
} 

可能有人请帮助我使这个“符号”的工作所有的数据类型,如“短”,“长”等

+0

当你说generic时,你的意思是一个节点可以在同一棵树中有一个int符号和一个字符串符号,或者你希望能够创建一个符号总是相同的树(例如字符串) –

+0

@BobVale实际上我正在读取一个二进制文件,以创建符号的频率(可能是1110111的形式)。 “符号”必须适用于1字节或2字节等。你现在明白了吗? – Sss

回答

2

如果我理解正确,你就基本上做到像

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 
      } 
    } 
} 
+0

服务器,感谢您的帮助,但如果freq是浮动的呢? – Sss

+1

你有2.5个特定符号出现吗? –

+0

haha​​ha ..好的,谢谢:) – Sss

1

所有你需要在这里使用的是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); 

我希望这有助于。

+0

感谢您的帮助,但我不'不得不使用Interface。 – Sss

+0

那么恐怕我不明白这个问题......对不起。 – MoonKnight