我需要通過反射獲取 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現在有什么問題嗎?我怎么解決這個問題 ?
1 回答

一只甜甜圈
TA貢獻1836條經驗 獲得超5個贊
應該做什么item.GetType().GetProperty(item.Name)?item是一個PropertyInfo實例。您并不是想要獲得它的屬性,而是想要獲得您的model.
因此,將您的代碼簡化為:
var value = item.GetValue(model) as string;
if (value?.Length > max)
{
return validate = true;
}
- 1 回答
- 0 關注
- 169 瀏覽
添加回答
舉報
0/150
提交
取消