简体   繁体   中英

using Explicit Interface Implementation

I am trying to change the property type in interface implementation class using explicit interface implementation.

interface ISample
{    
   object Value { get; set; }     
} 

class SampleA : ISample
{    
   SomeClass1 Value { get; set; } 

   object ISample.Value
    {    
        get { return this.Value; }
        set { this.Value = (SomeClass1)value; }
    }    
}


class SampleB : ISample
{

   SomeClass2 Value { get; set; } 

   object ISample.Value
    {    
        get { return this.Value; }
        set { this.Value = (SomeClass2)value; }    
    }    
}

class SomeClass1
{    
   string s1;    
   string s2;    
}

But when I need to pass in interface obj in a function, I cant access the objects of SomeClass1 or SomeClass2.

For eg:

public void MethodA(ISample sample)    
{    
  string str = sample.Value.s1;//doesnt work.How can I access s1 using ISample??    
}

I don't know if this is understandable, but I cant seem to get an easier way to explain this. Is there a way to access the properties of SomeClass1 using interface ISample?

Thanks

That is because you've received the object as the interface, so it doesn't know about the class's new property type. You would need to:

public void MethodA(ISample sample)
{
  if (sample is SampleA)
  {
    string str = ((SampleA)sample).Value.s1;
  }     
}

A better solution might be to use the visitor pattern - which would have implementations for handling the different ISample's.

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