C# 将对象强制转换为非显式实现的接口
是否有可能将对象强制转换到它不直接继承的接口?在下面的示例代码中,是否有任何方法可以将All实例转换为单个实例C# 将对象强制转换为非显式实现的接口,c#,inheritance,C#,Inheritance,是否有可能将对象强制转换到它不直接继承的接口?在下面的示例代码中,是否有任何方法可以将All实例转换为单个实例 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.WriteLi
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();
}
}
您将需要使用
请注意,与
接口
不同,您不能强制将一个具体类型转换为另一个具体类型(在本例中,您的强制转换为Single
),必须将局部变量类型从具体类型(Single
)更改为接口(IC
)。类All
实际上根本没有实现IC
(“间接继承”是另一回事)。听起来你在追求duck类型,而C#不支持(dynamic
不算在内)@Dai不,没有明确说明,但事实上它们共享相同的签名。只是想知道这是否可以实现,但猜测不可能;-)关键是在IC
中,您可以实现/添加许多新功能。将all
转换为IC之后,在这些场景中single
的行为会是什么代码>类型。因此它不受支持。谢谢。对于AllIC
实例,这是一个可能的解决方案,您不需要作为IC
。并且您将在转换为时获得运行时异常(单条)
因为AllIC
不是一个单曲
@SergeyBerezovskiy,我忽略了单曲
类。我已经更正了我的答案。
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();
}