不知何故,可以将对象强制转换为它不直接继承的接口?在下面的示例代码中,有没有办法将所有实例转换为单个实例?
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();
}
}发布于 2017-07-08 05:50:32
您将需要使用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();
}请注意,与interfaces不同,您不能将一个具体类型强制转换为另一个具体类型(在本例中,强制转换为Single),必须将局部变量类型从具体类型(Single)更改为接口(IC)。
https://stackoverflow.com/questions/44980069
复制相似问题