Get properties from derived class in base class

前端 未结 7 2258
面向向阳花
面向向阳花 2021-02-09 07:02

How do I get properties from derived class in base class?

Base class:

public abstract class BaseModel {
    protected static readonly Dictionary

        
7条回答
  •  面向向阳花
    2021-02-09 07:32

    If you must do literally fetch property of derived class from within base class, you can use Reflection, for example - like this...

    using System;
    public class BaseModel
    {
        public string getName()
        {
            return (string) this.GetType().GetProperty("Name").GetValue(this, null);
        }
    }
    
    public class SubModel : BaseModel
    {
        public string Name { get; set; }
    }
    
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                SubModel b = new SubModel();
                b.Name = "hello";
                System.Console.Out.WriteLine(b.getName()); //prints hello
            }
        }
    }
    

    This is not recommended, though, and you most probably should rethink your design like Matthew said.

    As for not throwing properties to your base classes -- you can try to decouple base and deriving classes into unrelated objects and pass them via constructors.

提交回复
热议问题