如何从抽象超类引用子类的字段?

时间:2012-10-04 18:17:37

标签: c# inheritance reflection

类似:How can I access an instance field in an abstract parent class via reflection?,但仅在名称中,没有人实际使用或引用那里的反射。

约束:

  • C#
  • 必须使用抽象类继承
  • 必须能够将字符串作为字段标识符传递(愿意协商)

    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
     }
    }
    

    我认为这需要反思,但不能完全绕过它。如何在此示例中访问Car字段?

  • 2 个答案:

    答案 0 :(得分:3)

    试试这个:

    [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();
        }
    }
    

    答案 1 :(得分:1)

    尝试这样的事情:

        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;
             }
        }