jeudi 8 août 2019

Get value of property with reflection in C#

i need to get value of property in C# with reflection .

i need to find lenght of string and compare to max .

i write this code :

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

and this for get value of property :

var lenght = item.GetType().GetProperty(item.Name).GetValue(cls, null);

but it show me this error :

  Message "Object does not match target type."    string

now whats the problem ? how can i solve this problem ?





Aucun commentaire:

Enregistrer un commentaire