计算对象中所有字符串属性的总长度
我有一个具有数百个属性的对象。 它们都是字符串。我如何计算所有属性放在一起的总长度?
我的尝试:
public static int GetPropertiesMaxLength(object obj)
{
int totalMaxLength=0;
Type type = obj.GetType();
PropertyInfo[] info = type.GetProperties();
foreach (PropertyInfo property in info)
{
// ?
totalMaxLength+=??
}
return totalMaxLength;
}
建议?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用 LINQ Sum() 和 Where() 方法:
PS: 启用 LINQ,您必须
使用 System.Linq
添加;编辑:更通用的方法
Using LINQ Sum() and Where() methods:
PS: To enable LINQ you've to add
using System.Linq
;EDIT: More generic approach
获取给定属性
PropertyInfo
使用
GetValue
方法传递包含对象且不带任何参数(除非这是一个索引属性 - 这会使事情变得更复杂):To get the value of a property given its
PropertyInfo
use theGetValue
method passing the containing object and no parameters (unless this is an indexed property – which would make things more complicated):像这样
Like this
假设所有属性都是公共的:
如果属性并非全部公共,那么您必须像这样组合所需的绑定标志
Assuming that all properties are public:
If the properties are not all public then you'll have to combine the needed binding flags like this
这是我的建议:
Here is my suggestion:
试试这个。
Try this.
您可以根据需要更改 where 子句。例如,如果您想排除静态或私有等。
You could alter the where clause to your needs. For example if you want to exclude statics or privates, etc.