简体   繁体   中英

how to access properties in derived class stored in a list of the base class

I am trying to work with lists of objects that all come from the same base class.

I have my base type (question) and derived types (3TQ, 2TQ)

Depending on the situation the list will all be of one or other derived type.

So all my interfaces deal with a list of the base type question.

But once I have the list in my grasp, I cant access the derived types.

So long story short - how does one extract a usable derived object from the list of the base objects? I feel this should be easy and that I am missing something really obvious.

You will have to use explicit casting, the code would look like this,

// This is the Child Class which derives from class Base.

Child c = new Child();

//UpCast can be done implicitly without any issues

Base b = c;

//Explicit conversion is required to cast the object back to derived.
Child c1 = (Child) b;

Now , since this is runtime operation, you will not get an error in case of incorrect casting, hence always make a check before casting. you can use "is" or "as" keyword, Below are the links that will give you more details.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is

Hope this helps

I think i get your intention. You can define virtual method in base class and have in overridden in both the derived classes as you mentioned (which will definitely be able to access property specific to that class. These overridden method might also require to return some thing your consuming code depends on that. Probably below code snippet help you visualize :

public class MyBaseClass
    {
        public virtual int MyMethod()
        {
            return default(int);
        }
    }

public class MyDerivedClass1:MyBaseClass
{
    public int MyProperty1 { get; set; }
    public override int MyMethod()
    {
        return MyProperty1;
    }
}

public class MyDerivedClass2 : MyBaseClass
{
    public int MyProperty2 { get; set; }
    public override int MyMethod()
    {
        return MyProperty2;
    }
}

public class MyConsumer
{
    List<MyBaseClass> baselist = new List<MyBaseClass>
    {
        new MyDerivedClass1 {MyProperty1=2 },
        new MyDerivedClass2 {MyProperty2=5 }
    };

    public void TestMethod()
    {
        foreach(var item in baselist)
        {
            var x = item.MyMethod();
            /* take care of your actual logic here*/
        }
    }

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