日期:2014-05-18  浏览次数:20832 次

C#基础扎实的高手请进
有两个问题需向各位前辈请教:
1、我定义了一个实体类C,它有N个bool属性。然后在界面用代码生成N个的checkbox,checkbox的名称便是C类里的其中一个属性。有没有法子,我在遍历CheckBox的时候,知道它对应于哪个属性?数目太多,不想一个一个比较

2、我重写VS自带的ListBox控件,定义了一个listBoxItem来存放每一个条目,如果绑定的对象是dataTable或List <listBoxItem> ,可以把其转换为listBoxItem对象,但如果是绑定其他未名称知道的实体集,如何转换呢?至今没找到好的解决法子

以上两个问题困扰了我2个晚上睡不好觉,如果您知道或有好的解决方式,还请告知。
谢谢!

------解决方案--------------------
设置属性值当然是可以的了,下面是代码

/// <summary>
/// 设置属性值
/// </summary>
/// <param name= "obj "> 设置属性的对象 </param>
/// <param name= "propertyName "> 属性名 </param>
/// <param name= "value "> 属性值 </param>
public static void SetPropertyValue(object obj, String propertyName, object value, object[] index)
{
Type t = obj.GetType();
PropertyInfo pi;

if (index != null)
{
if (index.Length > 0)
{
obj = GetPropertyValue(obj, propertyName, null);
t = obj.GetType();
propertyName = "Item ";
}
}

if (index != null)
{
Type[] types = new Type[index.Length];

for (int i = 0; i < types.Length; i++)
{
types[i] = index[i].GetType();
}

pi = t.GetProperty(propertyName, types);
}
else
{
pi = t.GetProperty(propertyName);
}

if (pi == null)
{
Exception e = new Exception(String.Format( "Unknown Property Name = {0} ", propertyName));
throw (e);
}

pi.SetValue(obj, value, index);
}
------解决方案--------------------
class a
{
string _propertyname= " "
public propertyname
{
get{ return _propertyname;}
set{ _propertyname=Value;}
}
}

a class1=new a();
class1.propetyname= "asdasdf ";
PropertyDescriptor member = TypeDescriptor.GetProperties(class1)[ "propertyname "];
object oldvalue=member.GetValue(class1);
MessageBox.Show(oldvalue.ToString())
member.SetValue(class1, "newvalue ");
MessageBox.Show(class1.propertyname);