我想创建一个通用的静态类。该类应通过每个属性,并检查是否为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;
}
}
我需要帮助来获取数组中当前元素的数量。
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;
}
如果您还想在实例对象而不是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>();