I have a method which uses some FieldInfo objects:
public static T SetFieldValue<T>(this T src, string propName, object value)
{
Type type = typeof(T);
FieldInfo propInfo = type.GetField(propName,
BindingFlags.Instance | BindingFlags.NonPublic);
Type propType = propInfo.FieldType;
var targetType = IsNullableType(propType)
? Nullable.GetUnderlyingType(propType) : propType;
value = Convert.ChangeType(value, targetType);
propInfo.SetValue(src, value);
return src;
}
Now I need some way of getting a PropertyInfo object from a specific FieldInfo this function returns, mainly because I specifically need the PropertyInfo.Name string, any thoughts on that?
Edit: Here's some more specific code, I use this method to get the difference between two objects:
public static List<Variance> DetailedCompare<T>(this T val1, T val2)
{
List<Variance> variances = new List<Variance>();
FieldInfo[] fi = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
foreach (FieldInfo f in fi) {
Variance v = new Variance();
v.Prop = f.Name;
v.valA = f.GetValue(val1);
v.valB = f.GetValue(val2);
if (v.valA != null) {
if (!v.valA.Equals(v.valB))
variances.Add(v);
} else if (v.valB != null) {
variances.Add(v);
}
}
return variances;
}
Then I use the returned fields to format a SQL query which I'll send to a webservice, to be more specific. But the FieldInfo.Name objects are generally something like k__BackingField or k__BackingField I need the PropertyInfo.Name, which is the correct name. Is there some way to create a PropertyInfo object from a FieldInfo object?
i got this in my old codes.
you can use PropertyInfo
msdn https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo?view=netframework-4.7.2
and if you want get all members in T
MemberInfo https://learn.microsoft.com/en-us/dotnet/api/system.reflection.memberinfo?view=netframework-4.7.2