【发布时间】:2017-09-06 14:39:09
【问题描述】:
我有以下代码:
public interface BaseInterface
{
int ID { get; }
}
public interface SpecialInterface1 : BaseInterface
{
int price { get; }
}
public interface SpecialInterface1 : BaseInterface
{
int xyz { get; }
}
public class Implementation1 : SpecialInterface
{
int price { get; }
int ID { get; internal set; }
}
public class Implementation2 : SpecialInterface
{
int xyz { get; }
int ID { get; internal set; }
}
现在在管理类中,我想将实现BaseInterface 的对象添加到列表中。
我知道我可以使用 as 或 is 将接口转换为实现,但在我的项目中,我有大约 10 个特殊接口,每个接口都有一个实现,所以我必须编写一个非常大的 if 语句.
public void Add(BaseInterface u, int id)
{
if (u is Implementation1)
{
((Implementation1)u).ID = id;
Units.Add(u);
}
if (u is Implementation2)
{
((Implementation2)u).ID = id;
Units.Add(u);
}
}
我的目标是 id 在实现之外是不可更改的,我将只提供我的 dll 之外的接口,因此没有人可以更改 id。
【问题讨论】:
-
您可以在任何情况下强制转换为 BaseInterface,因为它声明了 ID。不需要任何如果。
-
@sam 但是你需要一个强制转换来将接口的一个实例变成具体的实现,这就是这里正在做的事情。
-
@Servy 是的,但你不需要这样做。
-
@sam 是的,在显示的代码中确实如此。
-
您可以创建一个实现 BaseInterface 的 BaseImplementation 类,并为 ID 属性添加内部设置器,并使每个进一步的实现也从 BaseImplementation 继承,然后您可以将 Implementation 转换为您的 BaseImplementation并在您的管理类中设置 ID