Using an Explicit Interface Implementation
I am trying to change the type of a property in an interface implementation class using an 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 obj interface to a function, I cannot access SomeClass1 or SomeClass2 objects.
For example,
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 clear, but it seems to me that it’s easier for me to explain it. Is there a way to access the properties of SomeClass1 using the ISample interface?
thank
+3
source to share
1 answer
This is because you got the object as an interface, so it doesn't know about the type of the new class of the class. You will need:
public void MethodA(ISample sample)
{
if (sample is SampleA)
{
string str = ((SampleA)sample).Value.s1;
}
}
A better solution might be to use the visitor template , which will have implementations to handle different ISamples.
+1
source to share