读书人

非常深奥的有关问题!涉及索引器、装箱

发布时间: 2012-01-30 21:15:58 作者: rapoo

非常深奥的问题!涉及索引器、装箱、泛型等!综合技术!
应用场景:
在一个类中包含多种值类型的属性,现在希望通过构建多个索引器或是可以遍历访问的数组对象,来访问此类的实例中的多种类型属性。
比如string类型的索引器中索引0为“Name”属性,索引1为“Info”属性;而int类型的索引器中索引0为“ID”属性,索引1为“Age”属性。所有属性不单应可以读取,还应当能赋值,并且在类的实例中的属性发生改变时也能读取到改变后的值。

实现构想:

1.泛型索引器:
public <T> this <T> [int index]
{
get
{
//遍历比较属性并返回相应序列索引的指定类型的值
int x = 0;
if (ID.GetType() == typeof(T) && x++ == index) { return ID; }
if (Age.GetType() == typeof(T) && x++ == index) { return Age; }
if (Name.GetType() == typeof(T) && x++ == index) { return Name; }
if (Info.GetType() == typeof(T) && x++ == index) { return Info; }
...
return null;
}
set
{
int x = 0;
if (ID.GetType() == typeof(T) && x++ == index) { ID = value; }
if (Age.GetType() == typeof(T) && x++ == index) { Age = value; }
if (Name.GetType() == typeof(T) && x++ == index) { Name = value; }
if (Info.GetType() == typeof(T) && x++ == index) { Info = value; }
...
}
}
失败——索引器不支持泛型!

2.依靠索引器参数传递类型值:
public object this[int index,Type type]
{
...与上文类似,不再累述
}
失败——无法给强类型属性赋予object值!

3.装箱并放入泛型列表List <> 中
public List <object> 获取属性索引 <T> ()
{
List <object> list=new List <object> ();
object o = new object();
if (ID.GetType() == typeof(T)) { o=ID;list.Add(o); }
if (Age.GetType() == typeof(T)) { o=Age;list.Add(o); }
...
return list;
}
失败——装箱后无法和原属性挂接,双方各不相干,修改属性后在对方处无效。

4.用一个无意义的参数标识索引器,进行重载:
public int this[int index,int type]
{
get
{
switch(index)
{
case 0:return ID;
case 1:return Age;
...
default retun null;
}
}
set
{
....
}
}

public string this[int index,string type]
{
get
{
switch(index)
{


case 0:return Name;
case 1:return Info;
...
default retun null;
}
}
set
{
....
}
}
没做试验,但猜想可以成功,可是非常蹩脚,多余的那个参数根本无意义,很是不爽。

所以在此请教各位高人,有没有完美的可实现办法呢?

[解决办法]
public void 设置属性 <T> (int index, T value)
{
int x = 0;
foreach(PropertyInfo property in this.GetType().GetProperties()){
if(property.PropertyType == typeof(T) && x++ = index)
{
property.SetValue(value, this, null);
return;
}
}
}

public T 获取属性 <T> (int index)
{
int x = 0;
foreach(PropertyInfo property in this.GetType().GetProperties()){
if(property.PropertyType == typeof(T) && x++ = index)
{
return (T)property.GetValue(this, null);
}
}
}

读书人网 >C#

热点推荐