It's somehow possible to cast an object to an interface which it doesnt inherit directly? In my sample code below, is there any way to convert an All instance to a Single one?
public interface IA
{
void A();
}
public interface IB
{
void B();
}
public interface IC : IA, IB
{
}
public class All : IA, IB
{
public void A()
{
Console.Out.WriteLine("ALL A");
}
public void B()
{
Console.Out.WriteLine("ALL B");
}
}
public class Single : IC
{
public void A()
{
Console.Out.WriteLine("SINGLE A");
}
public void B()
{
Console.Out.WriteLine("SINGLE B");
}
}
class Program
{
static void Main()
{
All all = new All();
Single single = (Single)(all as IC); // Always null
single?.A();
}
}
You will need to use the Adapter Pattern .
class AllIC : IC {
private readonly All all;
public AllIC(All all) {
if( all == null ) throw new ArgumentNullException(nameof(all));
this.all = all;
}
public void A() => this.all.A();
public void B() => this.all.B();
}
static void Main()
{
All all = new All();
IC ic = new AllIC( all ); // Observe that `ic` is typed as interface `IC` instead of the concrete type `Single`.
ic.A();
}
Note that unlike interfaces
you cannot coerce one concrete type to another (in this case, your casting to Single
), you must change your local variable type from a concrete type ( Single
) to an interface ( IC
).
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.