我想扩展PropertyInfo类,以便它也可以包含属性值,而不需要像以下那样引用原始对象
public class PropertyInfoWithValue : PropertyInfo
{
private object value;
public object Value { get; set; }
public PropertyInfoWithValue(object value)
{
this.value = value;
}
}
但现在问题是我得到几个例外
`PropertyInfoWithValue does not implement the inherited abstract member System.Reflection.MemberInfo/PropertyInfo.XXXX`
我获得房产信息的方式
public static IEnumerable<PropertyInfoWithValue> GetColumns<T>(
this T obj, params Expression<Func<T, object>>[] lambda)
{
HashSet<string> set = new HashSet<string>(
lambda.Select(l => (l.Body as MemberExpression).Member as PropertyInfo)
.Select(x => x.Name)
);
if (set.Count == 0)
{
return obj.GetType().GetProperties().Select(p => new PropertyInfoWithValue(p.GetValue(obj, null))).ToList();
}
else
{
return obj.GetType().GetProperties().Where(p => set.Contains(p.Name)).Select(p => new PropertyInfoWithValue(p.GetValue(obj, null))).ToList();
}
}
答案 0 :(得分:1)
您必须要实现基类abstract
标记为PropertyInfo
的所有方法和属性,但我建议创建一个自定义类,以反映您尝试检索的数据。如果您仍然想要返回PropertyInfo
,因为您认为自己需要它,那么包装类可能更容易实现和理解。
示例:
public class PropertyInfoWithValue
{
PropertyInfo propertyInfo;
public PropertyInfoWithValue(PropertyInfo propertyInfo, object value)
{
this.propertyInfo = propertyInfo;
SetValue(value);
}
public object Value { get; private set; }
public void SetValue(object value)
{
this.Value = value;
}
public static explicit operator PropertyInfoWithValue(PropertyInfo propertyInfo)
{
if (propertyInfo == null)
return null;
// supply a default value, because we don't know it yet.
object value = null;
if (propertyInfo.PropertyType.IsValueType)
value = Activator.CreateInstance(propertyInfo.PropertyType);
return new PropertyInfoWithValue(propertyInfo, value);
}
public static explicit operator PropertyInfo(PropertyInfoWithValue
propertyInfoWithValue)
{
if (propertyInfoWithValue == null)
return null;
return propertyInfoWithValue.propertyInfo;
}
}
通过这种方式,您仍然可以通过将其转换为PropertyInfo
来获取:
PropertyInfo propertyInfo = (PropertyInfo)myPropertyInfoWithValue;