0
我遇到類和接口問題。 我想實現一個接口聲明一個方法,它採用實現的類的類型。 當我從這個類繼承時,該方法應該只採用繼承類的類型。確保實現接口和繼承時的參數類型
這可能嗎?
短代碼剪斷:
class Program
{
static void Main(string[] args)
{
Node node1 = new Node();
Node node2 = new Node();
Node node3 = new Node();
// Connect node2 to node1 and node3 to node1.
node1.connect(node2)
.connect(node3);
SomeNode node4 = new SomeNode();
SomeNode node5 = new SomeNode();
node4.connect(node5);
// node1.connect(node4); // This should not be possible because node1.connect() should only accept Node and not SomeNode.
}
}
interface INode
{
int Id { get; set; }
// Instead of INode, here should be the type of the implementing class or the type of the subclass (or the sub-subclass ...).
INode connect(INode node);
}
class Node : INode
{
public int Id { get; set; }
// This list MUST be protected and MUST be able to contain only objects of the current class type.
protected List<Node> connectedNodes;
// This should implement the interface mehtod but in subclasses, the type should not be Node but the type of the subclass.
// Of cause, this method should not be reimplemented in subclasses.
public Node connect(Node node)
{
this.connectedNodes.Add(node);
return this; // Enable chaining.
}
}
class SomeNode : Node
{
// Here should be some additional functionality but NOT the connect() method!
}
如果可能,它可能很醜。例如,如果節點不是節點,則可以引發異常。但是,這給運行時和不編譯時間檢查。 –