C# 在C中通过反射获取属性值

C# 在C中通过反射获取属性值,c#,.net,reflection,C#,.net,Reflection,我需要得到C中带有反射的属性值 我需要找到字符串的长度并与max进行比较 我写这段代码: public static bool ValidateWithReflection(T model) { bool validate = false; var cls = typeof(T); PropertyInfo[] propertyInfos = cls.GetProperties(); foreach (PropertyInf

我需要得到C中带有反射的属性值

我需要找到字符串的长度并与max进行比较

我写这段代码:

public static bool ValidateWithReflection(T model)
    {
        bool validate = false;
        var cls = typeof(T);
        PropertyInfo[] propertyInfos = cls.GetProperties();
        foreach (PropertyInfo item in propertyInfos)
        {
            var max = item.GetCustomAttributes<MaxLenghtName>().Select(x => x.Max).FirstOrDefault();
            if (max != 0)
            {
                var lenght = item.GetType().GetProperty(item.Name).GetValue(cls, null);
                if ((int)lenght > max)
                {
                    return validate = true;
                }
            }
        }
        return validate;
    }
现在有什么问题?如何解决此问题?

item.GetType.GetPropertyitem.Name应该做什么?项是PropertyInfo实例。你不是想得到它的属性,而是你的模型

因此,请将代码简化为:

var value = item.GetValue(model) as string;
if (value?.Length > max)
{
    return validate = true;
}

您没有在任何地方使用模型这一事实应该是一个提示。使用模型而不是cls,因为GetValue参数要求对象从中获取值。var lenght=item.GetType.GetPropertyitem.Name.GetValuemodel,null;cls只是一种类型,它没有任何值,因此无法从中获取值。您需要获取该类型的实际实例的值,而不是类型本身。其次,为什么要对GetValue使用索引覆盖并为其提供null?只要调用GetValueobj@ĴošħWilliard,仍然会显示该错误;仅当属性为静态时才正确;GetValuecls,模型;相反
var value = item.GetValue(model) as string;
if (value?.Length > max)
{
    return validate = true;
}