简体   繁体   中英

How to get the values from the base class in c# without using property name

I have a method which calls the sqlquery method of my dbcontext methods are below:

private IEnumerable<object> getRawDataDb(DependencySheet sheet, string name)
{
    switch(name)
    {
        case "DefaultData":
              return sqlQuery.Database.SqlQuery<DefaultData>(sheet.Query);

        case "OpenInventory":
               return sqlQuery.Database.SqlQuery<OpenInventory>(sheet.Query);

        case "CompQuals":
               return sqlQuery.Database.SqlQuery<CompQual>(sheet.Query);
    }

    return null;
}

Calling the above method from below

var rawData = getRawDataDb(dependentData, sheetName).ToList();

and then iterating it with foreach loop as below:

foreach(var raw in rawData)
{
    var tw = raw.GetType().BaseType.GetFields(BindingFlags.NonPublic|BindingFlags.Instance); 
}

Now while executing when I want to get the values shown below into the image which is getting in the raw object :

在此处输入图片说明

but I am not able to get the values and I have used gettype already.

thanks daman

If I understand, you have BaseClass:

public class BaseClass
{
    public int ID { get; set; }
    public string Name { get; set; }
}

And some inherited from it (for example OpenInventory):

public class OpenInventory : BaseClass
{
    public string AnotherProperty { get; set; }
}

Then you can write:

public IEnumerable<BaseClass> getRawDataDb(DependencySheet sheet, string name)
{
    //type declaration OpenInventory must be located at the same assembly with getRawDataDb
    var type = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.Name == name).First();

    var res = new List<BaseClass>();
    var source = sqlQuery.Database.SqlQuery(type, sheet.Query);

    foreach (var item in source)
        res.Add(item as BaseClass);

    return res;
}

And it will executed as you wanted:

var res = getRawDataDb(dependentData, sheetName).ToList();   

As a result you will be able to call BaseClass's properties explicitly:

res.First().ID

And you also can call another properties via explicit conversion:

(res.First() as OpenInventory).AnotherProperty;    

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