2014-02-20 81 views
0

什麼我不知道(學習目的):C#,類[]運營商和分配/複製

DdrRam memXMP=new DdrRam(); 
    memXMP.addType("overclock"); 
    memXMP.addType("low profile");    

    memXMP["low profile"]="lp"; // just trying to change the type of a ram  
    memXMP["overlock"]="oc"; //   
    int tmp=memXMP["lp"];  // gets id integer number of "lp" 

我學到了什麼/完成(成功):

DdrRam ven = new DdrRam(); 
    ven.addMemoryType("ddr4"); 
    ven.addMemoryType("ddr5"); 
    ven.addMemoryType("stacked dram"); 
    Console.WriteLine("ddr4 memory type id={0}",ven["ddr4"]); 
    Console.WriteLine("ddr5 memory type id={0}" , ven["ddr5"]); 
    Console.WriteLine("stacked dram memory type id={0}" , ven["stacked dram"]); 
    // getter is working as intended, 
    //output is: 
    ddr4 memory type id=0 
    ddr5 memory type id=1 
    stacked dram memory type id=2 

類是:

class DdrRam 
    { 
     List<string> memTypes; 
     public DdrRam() 
     { 
      memTypes=new List<string>(); 
     } 

     public void addMemoryType(string memAdd) 
     { 
      memTypes.Add(memAdd); 
     } 

     public int this[string prf] 
     { 
      get { return memTypes.IndexOf(prf); } 

      // set { memTypes[memTypes.IndexOf(strVal)] = value; } 
      // ven["ddr5"] = "double data rate 5"; 
      // cannot implicitly convert string to int 

     } 

     // public string this [string strVal] 
     // { 
     //  set { memTypes[memTypes.IndexOf(strVal)] = value; } 
     // } 
     // this makes [] an ambiguous call so I cant use. 

     ~DdrRam() 
     { 

     } 
    }; 

問題:如何重載=運算符,這樣我就可以使用[]賦值或複製了?

myClassInstanceNotAnArray["string index"]=someObject; 

回答

0

你可以做嘗試這樣做:

DdrRam memXMP=new DdrRam(); 
    memXMP.addType("overclock"); 
    memXMP.addType("low profile");  
    memXMP[memXMP.IndexOf("low profile")]="lp"; // just trying to change the type of a ram  
    memXMP[memXMP.IndexOf("overlock")]="oc"; 

通過的IndexOf你應該能夠去改變它!在名單上它與一個定期名單