gpt4 book ai didi

c# - 计算对象中所有字符串属性的总长度

转载 作者:行者123 更新时间:2023-11-30 14:38:35 27 4
gpt4 key购买 nike

我有一个具有 100 多个属性的对象。它们都是字符串。如何计算所有属性放在一起的总长度?

我的尝试:

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

建议?

最佳答案

使用 LINQ Sum()Where()方法:

public static int GetTotalLengthOfStringProperties(object obj)
{
Type type = obj.GetType();
IEnumerable<PropertyInfo> info = type.GetProperties();

int total = info.Where(p => p.PropertyType == typeof (String))
.Sum(pr => (((String) pr.GetValue(obj, null))
?? String.Empty).Length);
return total;
}

PS:要启用 LINQ,您必须添加using System.Linq

编辑:更通用的方法

/// <summary>
/// Gets a total length of all string-type properties
/// </summary>
/// <param name="obj">The given object</param>
/// <param name="anyAccessModifier">
/// A value which indicating whether non-public and static properties
/// should be counted
/// </param>
/// <returns>A total length of all string-type properties</returns>
public static int GetTotalLengthOfStringProperties(
object obj,
bool anyAccessModifier)
{
Func<PropertyInfo, Object, int> resolveLength = (p, o) =>
((((String) p.GetValue(o, null))) ?? String.Empty).Length;

Type type = obj.GetType();
IEnumerable<PropertyInfo> info = anyAccessModifier
? type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public |
BindingFlags.Instance | BindingFlags.Static)
: type.GetProperties();

int total = info.Where(p => p.PropertyType == typeof (String))
.Sum(pr => resolveLength(pr, obj));
return total;
}

关于c# - 计算对象中所有字符串属性的总长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7765249/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com