C#查找数组中存在的元素数

问题描述 投票:0回答:2

我想创建一个通用的静态类。该类应通过每个属性,并检查是否为array。如果结果为true,则类应检查类中存在多少个元素并返回该数字。

我到目前为止所做的:

 public static class Helper<T> where T : class
    {
        private static int _counter = 0;
        public static int Counter()
        {
            Type type = typeof(T);
            foreach (var property in type.GetProperties())
            {
                if (property.PropertyType.IsArray)
                {

                }
            }

            return _counter;
        }
}

我需要帮助来获取数组中当前元素的数量。

c# .net .net-core
2个回答
1
投票
    public static int Counter()
    {
        Type type = typeof(T);
        foreach (var property in type.GetProperties())
        {
            Console.WriteLine(property.Name);
            if (property.PropertyType.IsArray)
            {
                var array = property.GetValue(null, null) as Array;
                Console.WriteLine(array.Length);
            }
        }

        return _counter;
    }

示例:https://dotnetfiddle.net/2ICron


0
投票

如果您还想在实例对象而不是Type上使用它,则可以做某事。像这样(删除Helper的通用类型,并使Counter方法通用):

public static class Helper
{
    public static int Counter<T>() where T : class => Counter(typeof(T));

    public static int Counter(object objectTCount) => Counter(objectTCount.GetType());

    public static int Counter(Type type)
    {
        int _counter = 0;
        foreach (var property in type.GetProperties())
        {
            if (property.PropertyType.IsArray)
            {
                var array = property.GetValue(null, null) as Array;
                var lenth = array.Length;

                // do s.th. with your counter
            }
        }

        return _counter;
    }
}

然后您可以像这样使用它:

var x = new TestClass();
Helper.Counter(x);
Helper.Counter<TestClass>();

© www.soinside.com 2019 - 2024. All rights reserved.