简体   繁体   中英

Instantiate derived class properties of specific type from base class

Instantiate derived class properties of specified type from base class

Sample:

public class TBaseModel{

    public TBaseModel(){
        //here i want to list all dervied class peoperties of type DbSet and Instantiate it here.
    }

}

public class TDataModel : TBaseModel
{
    public DbSet cars {set ; get ;}

    public TDataModel (){
        cars  = new DbSet(); // i don't want to do this
    }

}

the solutions is loop to all current class properties and create new instance based on property class type and set the new instance back to current class .

 public class TBaseClass
    {

    public TBaseClass()
    {

        Type thisClass = this.GetType();
        PropertyInfo[] info = thisClass.GetProperties();
        foreach (var prop in info)
        {
            if (typeof(TDataModel).IsAssignableFrom(prop.PropertyType))
            {
                object newModel = Activator.CreateInstance(prop.PropertyType);
                prop.SetValue(this, newModel, null);
            }


        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM