简体   繁体   中英

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 ?

What is item.GetType().GetProperty(item.Name) supposed to do? item is a PropertyInfo instance. You're not looking to get properties of that, but of your model .

So simplify your code to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM