C#,class []运算符和赋值/复制

时间:2014-02-20 21:49:16

标签: c# operator-overloading

我想知道(学习目的):

  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;

1 个答案:

答案 0 :(得分: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,你应该能够改变它!在列表中,它使用常规列表