【发布时间】: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