简体   繁体   English

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

[英]Get value of property with reflection in C#

i need to get value of property in C# with reflection . 我需要通过反射获取C#中的属性值。

i need to find lenght of string and compare to max . 我需要找到字符串的长度并与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.GetType().GetProperty(item.Name)应该做什么? item is a PropertyInfo instance. itemPropertyInfo实例。 You're not looking to get properties of that, but of your model . 你不希望得到的是性能,而是你的model

So simplify your code to this: 因此,将您的代码简化为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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