开发者

Decide property to use at runtime

I have employee class which contain more than 50 properties.开发者_JAVA技巧 I display all property name using PropertyInfo class on checkedboxlist on windows form. User can select more than one property to display in report. lets assume user selected name, title, phone, address then i need to get all in string and need to display it on report.

I can easily do this with if or switch but is there any other better way to do this instead of writing more than 50 switch statement?


You can use PropertyInfo to get the value as well (if this is what you mean):

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


When you generate the name of the property to display in the checkboxlist, also create an Expression that will retrieve the string representation of that property. Then for each checked item, run the expression on the current employee instance.


You could loop through the selected properties and get their values via the PropertyInfo list you've already used;

//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); 
}

Disclaimer: This isn't tested, or even compiled, but should give a good idea of what's required.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜