Imagine the following
A type T has a field Company. When executing the following method it works perfectly:
Type t = typeof(T);
t.GetProperty("Company")
Whith the following call I get null though
Type t = typeof(T);
t.GetProperty("company", BindingFlags.IgnoreCase)
Anybody got an idea?
You've overwritten the default look-up flags, if you specify new flags you need to provide all the info so that the property can be found. For example: BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance
You need to add BindingFlags.Public | BindingFlags.Instance
BindingFlags.Public | BindingFlags.Instance
Thanks, this really helped me out in a pinch today. I had audit information saved, but with incorrect casing on the property names. (The auditing is built into a datalayer.) Anyway so I had to add IgnoreCase as a binding flag, but then it still didn't work, till my coworker found this answer. The resulting function:
public static void SetProperty(Object R, string propertyName, object value)
{
Type type = R.GetType();
object result;
result = type.InvokeMember(
propertyName,
BindingFlags.SetProperty |
BindingFlags.IgnoreCase |
BindingFlags.Public |
BindingFlags.Instance,
null,
R,
new object[] { value });
}
This is part of a class I call DotMagic.
public static bool HasProperty(this object obj, string propertyName)
{
var properties = obj.GetType().GetProperties();
var count = properties.Where(o => o.Name.ToUpper() == propertyName.ToUpper()).Count();
return count > 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.