C # How to compress an object

I have the following list of slide objects. Based on the value of object 'type' var, I want to update the Slide object in the list. Is it possible?

foreach(Slide slide in slidePack.slides)
{
    if(slide.type == SlideType.SECTION_MARKER)
    {
      //upcast Slide to Section
    }
}

Sectionextends Slideand adds another parameter.

+5
source share
7 answers

Here is the correct way to handle this cast.

Edit: there are ways to develop programs that don't need the test / role you are looking for, but if you run into a situation where you need to try to shift the C # object to some type and process it in different ways depending on success, this is definitely way to do it.

Section section = slide as Section;
if (section != null)
{
    // you know it a section
}
else
{
    // you know it not
}
+7
source

Yes you can do it:

Section section = (Section)slide;

... or:

Section section = slide as Section;

, , slide Section, null, .

+9
Section section = (Section)slide;

- desgn.

+2

( ...)

. , ( ) . , . , .

:

class ClassWithX 
{
    public void X() {} 
}

class ClassWithXY 
{ 
    public void X() {} 

    public void Y() {}
}

class Test
{
    public static void Main(string[] args)
    {
        ClassWithX x = new ClassWithX();
        ((ClassWithXY) x).Y(); // Downcast, but x of type ClassWithX does not have Y()
    }
}

, .

+2

:

 Section section = (Section) slide;
+1
foreach(Slide slide in slidePack.slides)
{
     if(slide.type == SlideType.SECTION_MARKER)
     {
         Section sec = (Section)slide;

         //use sec.SectionProperty
     }
}
+1

, /

foreach(Section section in slidePack.slides.OfType<Section>())
{
    // Handle the current section object
}
0

All Articles