决定在运行时使用的属性

时间:2011-03-28 12:32:59

标签: c#

我的员工类包含50多个属性。我在Windows窗体上的checkedboxlist上使用PropertyInfo类显示所有属性名称。 用户可以选择多个属性以在报告中显示。让我们假设用户选择了名称,标题,电话,地址,然后我需要在字符串中获取所有内容,并且需要在报告中显示它。

我可以使用if或switch轻松完成此操作但是还有其他更好的方法来执行此操作而不是编写超过50个switch语句吗?

3 个答案:

答案 0 :(得分:1)

当您生成要在复选框列表中显示的属性的名称时,还要创建一个将检索该属性的字符串表示形式的Expression。 然后,对于每个选中的项目,在当前员工实例上运行表达式。

答案 1 :(得分:1)

您也可以使用PropertyInfo获取值(如果这是您的意思):

        PropertyInfo propertyInfo = catalog.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)
            .Where(x => x.Name == propertyName).SingleOrDefault();
        object propertyValue = propertyInfo.GetGetMethod().Invoke(customer);

答案 2 :(得分:1)

您可以遍历所选属性并通过您已使用过的PropertyInfo列表获取其值;

//Say you have a  Props instance defined as Generic.List(Of PropertyInfo) 
//and an instance of your class named Inst 
string[] selectedProps = {"Prop1","Prop2"}; 
string ret = ""; 
foreach (PropertyInfo pi in Props.Where(p => return selectedProps.Contains(p.Name))) {
    ret &= ret & pi.GetValue(Inst,Nothing); 
}

免责声明:这不是经过测试,甚至未经过编译,但应该很好地了解所需要的内容。

相关问题