How can I refer to a subclass field from an abstract superclass?

Seems like: How can I access the instance field in an abstract parent class through reflection? but only by name no one uses or finds reflection there.

Limitations:

C # Must use an abstract class for inheritance Must be able to pass a string as a field identifier (wanting to agree)
public class ViewModel : BaseClass { public Car Car { get; set; } } public abstract class BaseClass { public object GetField(string field){ //return Car if .GetField("Car") is called } } 

I suppose this requires reflection, but I could not completely circle my head around him. How to access a field car, as in this example?

+4
source share
2 answers

Try the following:

 [TestFixture] public class TravisSerialisationTest { [Test] public void GetPropertyValueTest() { var volvo = "Volvo"; var viewModel = new ViewModel() { Car = volvo }; var field = viewModel.GetField(() => viewModel.Car); Assert.AreEqual(volvo,field); } } public class ViewModel : BaseClass { public string Car { get; set; } } public abstract class BaseClass { public T GetField<T>(Expression<Func<T>> propertyExpression ) { return propertyExpression.Compile().Invoke(); } } 
+3
source

Try something like this:

  public class ViewModel : BaseClass { public string Car { get; set; } } public abstract class BaseClass { public object GetField(string name) { MemberInfo member = GetType() .GetMember( name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static ) .FirstOrDefault(); if(member == null) { return null; } PropertyInfo property = member as PropertyInfo; if(property != null) { return property.GetValue( this, null ); } FieldInfo field = member as FieldInfo; if(field != null) { return field.GetValue( this ); } return null; } } 
+1
source

Source: https://habr.com/ru/post/1437860/


All Articles