C# get fields with reflection
In C# ho开发者_开发知识库w do you use reflection to get variables that doesn't have getters/setters? For example the getValue method below will work for d2, but not d1.
public class Foo {
public String d1;
public String d2 { get; set; }
public object getValue(String propertyName){
return this.GetType().GetProperty(propertyName).GetValue(this, null);
}
}
d1
is not a property. It is a field. Use the reflection methods for Fields instead.
public class Foo {
public String d1;
public String d2 { get; set; }
public object getValue(String propertyName){
var member = this.GetType().GetMember(propertyName).Single();
if (member is PropertyInfo)
{
return ((PropertyInfo)member).GetValue(this, null);
}
else if (member is FieldInfo)
{
return ((FieldInfo)member).GetValue(this);
}
else throw new ArgumentOutOfRangeException();
}
}
d1
is not a property. It's a field. You would use this.GetType().GetField
to retrieve it via reflection.
public object getFieldValue(String fieldName){
return this.GetType().GetField(fieldName).GetValue(this);
}
What you are probably trying to is make getValue return the value of a property or field. You can use GetMember
can tell you if it is a property or a field. For example:
public object getValue(String memberName) {
var member = this.GetType().GetMember(memberName).Single();
if (member.MemberType == MemberTypes.Property) {
return ((PropertyInfo)member).GetValue(this, null);
}
if (member.MemberType == MemberTypes.Field) {
return ((FieldInfo)member).GetValue(this);
}
else
{
throw new Exception("Bad member type.");
}
}
You have to use the GetField method.
Msdn: Type.GetField()
精彩评论