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

发布于 2024-12-09 13:26:18 字数 434 浏览 4 评论 0 原文

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

我的尝试:

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

建议?

I have an object with 100s of properties.
they are all strings.How can I calculate the total length of all properties put together?

MyAttempt:

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

Suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

断念 2024-12-16 13:26:18

使用 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,您必须使用 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;
}

Using LINQ Sum() and Where() methods:

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: To enable LINQ you've to add using System.Linq;

EDIT: More generic approach

/// <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;
}
吲‖鸣 2024-12-16 13:26:18

获取给定属性 PropertyInfo 使用 GetValue 方法传递包含对象且不带任何参数(除非这是一个索引属性 - 这会使事情变得更复杂):

public static int GetPropertiesMaxLength(object obj) {
  int totalMaxLength=0;
  Type type = obj.GetType();
  PropertyInfo[] info = type.GetProperties();
  foreach (PropertyInfo property in info) {
     if (property.PropertyType == typeof(string)) {
       string value = property.GetValue(obj, null) as string;
       totalMaxLength += value.Length;
    }
  }
  return totalMaxLength;
}

To get the value of a property given its PropertyInfo use the GetValue method passing the containing object and no parameters (unless this is an indexed property – which would make things more complicated):

public static int GetPropertiesMaxLength(object obj) {
  int totalMaxLength=0;
  Type type = obj.GetType();
  PropertyInfo[] info = type.GetProperties();
  foreach (PropertyInfo property in info) {
     if (property.PropertyType == typeof(string)) {
       string value = property.GetValue(obj, null) as string;
       totalMaxLength += value.Length;
    }
  }
  return totalMaxLength;
}
彩扇题诗 2024-12-16 13:26:18

像这样

public static int GetPropertiesMaxLength(object obj)
{
    int totalMaxLength=0;
    Type type = obj.GetType();
    PropertyInfo[] info = type.GetProperties();
    foreach (PropertyInfo property in info)
    {
        totalMaxLength+= property.GetValue(obj, null).ToString().Length;
    }
    return totalMaxLength;
}

Like this

public static int GetPropertiesMaxLength(object obj)
{
    int totalMaxLength=0;
    Type type = obj.GetType();
    PropertyInfo[] info = type.GetProperties();
    foreach (PropertyInfo property in info)
    {
        totalMaxLength+= property.GetValue(obj, null).ToString().Length;
    }
    return totalMaxLength;
}
屋檐 2024-12-16 13:26:18

假设所有属性都是公共的:

Object objValue = property.GetValue(obj, null);
if(objValue  != null)
  totalMaxLength += obj
Value.ToString().Length;

如果属性并非全部公共,那么您必须像这样组合所需的绑定标志

Object objValue = property.GetValue(obj, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static /* etc... */, null, null, null);

Assuming that all properties are public:

Object objValue = property.GetValue(obj, null);
if(objValue  != null)
  totalMaxLength += obj
Value.ToString().Length;

If the properties are not all public then you'll have to combine the needed binding flags like this

Object objValue = property.GetValue(obj, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static /* etc... */, null, null, null);
清风疏影 2024-12-16 13:26:18

这是我的建议:

    public static int GetPropertiesMaxLength(object obj)
    {
        int totalMaxLength = 0;
        Type type = obj.GetType();
        PropertyInfo[] info = type.GetProperties();
        foreach (PropertyInfo property in info)
        {
            var value = property.GetValue(obj, null) as string;
            if (!string.IsNullOrEmpty(value))
            {
                totalMaxLength += value.Length;
            }
        }
        return totalMaxLength;
    }

Here is my suggestion:

    public static int GetPropertiesMaxLength(object obj)
    {
        int totalMaxLength = 0;
        Type type = obj.GetType();
        PropertyInfo[] info = type.GetProperties();
        foreach (PropertyInfo property in info)
        {
            var value = property.GetValue(obj, null) as string;
            if (!string.IsNullOrEmpty(value))
            {
                totalMaxLength += value.Length;
            }
        }
        return totalMaxLength;
    }
谁的新欢旧爱 2024-12-16 13:26:18
public static int GetPropertiesMaxLength(object obj)
{
    Type type = obj.GetType();
    PropertyInfo[] info = type.GetProperties();
    int totalMaxLength = info.Sum(prop => (prop.GetValue(prop, null) as string).Length);        
    return totalMaxLength;
}

试试这个。

public static int GetPropertiesMaxLength(object obj)
{
    Type type = obj.GetType();
    PropertyInfo[] info = type.GetProperties();
    int totalMaxLength = info.Sum(prop => (prop.GetValue(prop, null) as string).Length);        
    return totalMaxLength;
}

Try this.

一个人的夜不怕黑 2024-12-16 13:26:18
        int count = value.GetType()
            .GetProperties()
            .Where(p => p.PropertyType == typeof (string) && p.CanRead)
            .Select(p => (string) p.GetValue(value, null))
            .Sum(s => (string.IsNullOrEmpty(s) ? 0 : s.Length));

您可以根据需要更改 where 子句。例如,如果您想排除静态或私有等。

        int count = value.GetType()
            .GetProperties()
            .Where(p => p.PropertyType == typeof (string) && p.CanRead)
            .Select(p => (string) p.GetValue(value, null))
            .Sum(s => (string.IsNullOrEmpty(s) ? 0 : s.Length));

You could alter the where clause to your needs. For example if you want to exclude statics or privates, etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文