2011-08-24 37 views
1

我想实现一个C#类的字符串索引器,但是当你设置一个属性字典获取设置,而不是属性。这可能是简单的,我错过了,我只是看不到它。C#类索引设置字典不属性

objFiveProp temp = new objFiveProp(); 
temp["index1"] = 3; 

设置temp._items [ “index1之间”]值至3。

类:

public class objFiveProp 
{ 

    #region Properties 
    private Dictionary<string, int> _items; 
    public int this[string key] 
    { 
     get { return _items[key]; } 
     set { _items[key] = value; } 
    } 

    public int index1 { get; set; } 
    public int index2 { get; set; } 
    public int index3 { get; set; } 
    public int index4 { get; set; } 
    public int index5 { get; set; } 

    #endregion 
    #region Constructor 

    public objFiveProp() 
    { 
     index1 = 0; 
     index2 = 0; 
     index3 = 0; 
     index4 = 0; 
     index5 = 0; 
     _items = new Dictionary<string, int>(); 
     _items.Add("index1", index1); 
     _items.Add("index2", index2); 
     _items.Add("index3", index3); 
     _items.Add("index4", index4); 
     _items.Add("index5", index5); 

    } 

    #endregion 

} 

回答

2

这就是它的工作原理。该字典包含一个拷贝你用来设置它的整数 - 不是对属性的引用。

我会使用类似解决这个:

public class objFiveProp 
{ 
    private Dictionary<string, int> _items; 
    public int this[string key] 
    { 
     get { return _items[key]; } 
     set { _items[key] = value; } 
    } 

    public int Index1 
    { 
     get { return this["index1"]; } 
     set { this["index1"] = value; } 
    } 
    public int Index2 
    { 
     get { return this["index2"]; } 
     set { this["index2"] = value; } 
    } 

    // .... 

    public objFiveProp() 
    { 
     _items = new Dictionary<string, int>(); 
     _items.Add("index1", index1); 
     _items.Add("index2", index2); 
     _items.Add("index3", index3); 
     _items.Add("index4", index4); 
     _items.Add("index5", index5);  
    } 

#endregion 

这会导致你的性总是拉存储在你的字典中的值,以及保存在那里,所以没有价值的两个副本。

0

int是值类型,不是引用类型。当您在_items中设置值时,即使您最初从属性中添加了它,它也不会设置该属性。是基于值类型

MSDN

变量直接包含值。 将一个值类型变量赋值给另一个值将复制包含的 值。这与引用类型变量 的赋值不同,后者将引用复制到对象而不是对象本身。

如果你真正需要的是能够既从索引和属性访问你的数据,最简单的方法之一将是正是如此重写你的属性:

public int indexN 
{ 
    get { return _items["indexN"]; } 
    set { _items["indexN"] = value; } 
} 

另一种方法是使用反射在索引器的setter:

public int this[string key] 
{ 
    get { return _items[key]; } 
    set 
    { 
     _items[key] = value; 
     PropertyInfo prop = this.GetType().GetProperty(key); 
     if (prop != null) 
     { 
      prop.SetValue(this, null); 
     } 
    } 
} 

但请记住,反映相对很慢

还有其他的方法可以完成你想要做的事情,但也许最好的解决方案就是不要这样做。为您的课程选择最佳的界面,无论是索引器还是属性,并坚持使用它。你的代码会更易于维护(你不需要维护两个公共接口到你的类的数据)并且更具可读性(其他编码人员不需要知道索引器和属性是同一件事情)。干杯!

0

这是因为在索引集方法要设置字典项

public int this[string key] 
    { 
     get { return _items[key]; } 
     set { _items[key] = value; } //here you are setting the value of dictionary item not the property 
    } 

要么的值,对于索引1,索引2创建单独的属性等或在集方法上面加检查,脏溶液尽管,根据键的值设置成员变量的值;例如:

set { 
    _items[key] = value; 
    if(key == "index1") 
     index1 = value; 
}