.net 如何遍历一个类的所有属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/531384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through all the properties of a class?
提问by Sachin Chavan
I have a class.
我有一堂课。
Public Class Foo
Private _Name As String
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private _Age As String
Public Property Age() As String
Get
Return _Age
End Get
Set(ByVal value As String)
_Age = value
End Set
End Property
Private _ContactNumber As String
Public Property ContactNumber() As String
Get
Return _ContactNumber
End Get
Set(ByVal value As String)
_ContactNumber = value
End Set
End Property
End Class
I want to loop through the properties of the above class. eg;
我想遍历上述类的属性。例如;
Public Sub DisplayAll(ByVal Someobject As Foo)
For Each _Property As something In Someobject.Properties
Console.WriteLine(_Property.Name & "=" & _Property.value)
Next
End Sub
回答by Brannon
Use Reflection:
使用反射:
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}
for Excel - what tools/reference item must be added to gain access to BindingFlags, as there is no "System.Reflection" entry in the list
对于 Excel - 必须添加哪些工具/参考项才能访问 BindingFlags,因为列表中没有“System.Reflection”条目
Edit: You can also specify a BindingFlags value to type.GetProperties():
编辑:您还可以将 BindingFlags 值指定为type.GetProperties():
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);
That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).
这会将返回的属性限制为公共实例属性(不包括静态属性、受保护的属性等)。
You don't need to specify BindingFlags.GetProperty, you use that when calling type.InvokeMember()to get the value of a property.
您不需要指定BindingFlags.GetProperty,您可以在调用type.InvokeMember()获取属性值时使用它。
回答by Marc Gravell
Note that if the object you are talking about has a custom property model (such as DataRowViewetc for DataTable), then you need to use TypeDescriptor; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):
请注意,如果您正在谈论的对象具有自定义属性模型(例如DataRowView等DataTable),那么您需要使用TypeDescriptor; 好消息是,这对于常规课程仍然可以正常工作(甚至可以比反射快得多):
foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}
This also provides easy access to things like TypeConverterfor formatting:
这也提供了TypeConverter对格式化等内容的轻松访问:
string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));
回答by Sachin Chavan
VB version of C# given by Brannon:
Brannon 给出的 C# 的 VB 版本:
Public Sub DisplayAll(ByVal Someobject As Foo)
Dim _type As Type = Someobject.GetType()
Dim properties() As PropertyInfo = _type.GetProperties() 'line 3
For Each _property As PropertyInfo In properties
Console.WriteLine("Name: " + _property.Name + ", Value: " + _property.GetValue(Someobject, Nothing))
Next
End Sub
Using Binding flags in instead of line no.3
使用绑定标志代替第 3 行
Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Instance
Dim properties() As PropertyInfo = _type.GetProperties(flags)
回答by NicoJuicy
Reflection is pretty "heavy"
反射相当“重”
Perhaps try this solution: //C#
也许试试这个解决方案://C#
if (item is IEnumerable) {
foreach (object o in item as IEnumerable) {
//do function
}
} else {
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) {
if (p.CanRead) {
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, null)); //possible function
}
}
}
'VB.Net
'VB.Net
If TypeOf item Is IEnumerable Then
For Each o As Object In TryCast(item, IEnumerable)
'Do Function
Next
Else
For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
If p.CanRead Then
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing)) 'possible function
End If
Next
End If
Reflection slows down +/- 1000 x the speed of a method call, shown in The Performance of Everyday Things
反射减慢了 +/- 1000 x 方法调用的速度,如The Performance of Everyday Things 中所示
回答by 01F0
Here's another way to do it, using a LINQ lambda:
这是使用 LINQ lambda 的另一种方法:
C#:
C#:
SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));
VB.NET:
VB.NET:
SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))
回答by Chris Go
This is how I do it.
我就是这样做的。
foreach (var fi in typeof(CustomRoles).GetFields())
{
var propertyName = fi.Name;
}
回答by Hyman
private void ResetAllProperties()
{
Type type = this.GetType();
PropertyInfo[] properties = (from c in type.GetProperties()
where c.Name.StartsWith("Doc")
select c).ToArray();
foreach (PropertyInfo item in properties)
{
if (item.PropertyType.FullName == "System.String")
item.SetValue(this, "", null);
}
}
I used the code block above to reset all string properties in my web user control object which names are started with "Doc".
我使用上面的代码块来重置我的 Web 用户控件对象中所有名称以“Doc”开头的字符串属性。

