如何通过反射获取c#中Class属性的名称和值
问题描述:
公共类人员
{
公共字符串名称{get; set;} //通过模型类获取
.. 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 ...