【问题标题】:Get value of property with reflection in C#在 C# 中通过反射获取属性的值
【发布时间】:2019-08-08 13:22:16
【问题描述】:

我需要通过反射在 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;
    }

这用于获取财产价值:

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

但它显示了这个错误:

  Message "Object does not match target type."    string

现在有什么问题?我该如何解决这个问题?

【问题讨论】:

  • 你没有在任何地方使用model这一事实应该是一个提示。
  • 使用model 而不是cls,因为GetValue 参数要求对象从中获取值。 var lenght = item.GetType().GetProperty(item.Name).GetValue(model, null);
  • cls 只是类型,它没有任何值,所以你不能 getValue 从它。您需要在该类型的实际实例上获取值,而不是类型本身。其次,为什么要为GetValue 使用索引覆盖并为其提供null?只需致电GetValue(obj)
  • @ĴošħWilliard 仍然告诉我这个错误
  • .GetValue(cls, null); 仅当属性为 static 时才是正确的;改为GetValue(cls, model);

标签: c# .net reflection


【解决方案1】:

item.GetType().GetProperty(item.Name) 应该做什么? item 是一个 PropertyInfo 实例。你不是想获得它的属性,而是你的model

所以将你的代码简化为:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    相关资源
    最近更新 更多