如何通过反射获取c#中Class属性的名称和值 [英] How to get name and values of properties of properties of Class in c# through reflection

查看:585
本文介绍了如何通过反射获取c#中Class属性的名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

公共类人员

{

公共字符串名称{get; set;} //通过模型类获取

.. < br $> b $ b

...

}



公共班级员工

{

公共人员{get; set}

}



公共类型号:员工

{

}







b / b










。 ..





...





模型模型=新模型();





需要通过模型类获取Person类属性的名称和值通过反思....请帮助Iam卡住

Public class Person
{
public string name{get;set;}//get this via Model class
..

...
}

public class Employee
{
public Person person{get;set}
}

public class Model:Employee
{
}









...


...


Model model=new model();


Need to get the Names and values of properties of Person class via model class through reflection ....Please Help Iam stuck

推荐答案

看看这个:将列表转换为数据表 [ ^ ] - 它获取属性名称和值。
Have a look at this: Converting a List to a DataTable[^] - it gets the property names and values.


这是一个VB解决方案 - 当然是VB而不是C# - 但我通常使用VB。

但是大多数情况下,你需要的是.Net,应该很容易转换为C#...

Here is a VB-Solution - of course VB and not C# - but I normally work with VB.
But most of that, what is necessary for you, is .Net and should be easy converted to C# ...
Public Shared Function GetProperty(ByVal component As Object, ByVal propertyName As String) As Object
    Try
        Dim pd As System.ComponentModel.PropertyDescriptor = System.ComponentModel.TypeDescriptor.GetProperties(component)(propertyName)

        Return pd.GetValue(component)
    Catch
        Return Nothing
    End Try
End Function


Public Shared Function GetPropertyList(ByVal component As Object) As String()
    Dim pis As System.Reflection.PropertyInfo() = component.GetType().GetProperties()

    Dim myLen As Integer = pis.GetLength(0) - 1
    Dim myArray(myLen) As String
    For i As Integer = 0 To myLen
        myArray(i) = pis(i).Name
    Next

    Return myArray
End Function





但实际上没有别的东西可以作为OriginalGriff发布的解决方案......



But it is in fact nothing else as the posted Solution of OriginalGriff ...


这篇关于如何通过反射获取c#中Class属性的名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆