Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 决定在运行时使用的属性_C# - Fatal编程技术网

C# 决定在运行时使用的属性

C# 决定在运行时使用的属性,c#,C#,我有一个包含50多个属性的employee类。我在windows窗体的checkedboxlist上使用PropertyInfo类显示所有属性名。 用户可以选择多个属性以在报告中显示。让我们假设用户选择的名称、标题、电话、地址,然后我需要得到所有的字符串,并需要将其显示在报告中 使用if或switch可以很容易地做到这一点,但是有没有其他更好的方法来实现这一点,而不是编写超过50条switch语句?当您生成要显示在复选框列表中的属性名称时,还要创建一个表达式来检索该属性的字符串表示形式。 然后,

我有一个包含50多个属性的employee类。我在windows窗体的checkedboxlist上使用PropertyInfo类显示所有属性名。 用户可以选择多个属性以在报告中显示。让我们假设用户选择的名称、标题、电话、地址,然后我需要得到所有的字符串,并需要将其显示在报告中


使用if或switch可以很容易地做到这一点,但是有没有其他更好的方法来实现这一点,而不是编写超过50条switch语句?

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

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


您可以循环选择的属性,并通过已经使用的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); 
}
免责声明:这没有经过测试,甚至没有经过编译,但应该能够很好地了解需要什么

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