与 Eric 关于不可空引用类型的博客文章类似,问题的解决方案似乎微不足道,但显然并非如此。
为什么不能在 c# 中添加结构类型?如果像下面的(坏)示例这样的东西刚刚被放入语言中,会出现什么问题?
public structural interface INode
{
INode Next {get;}
}
class MyLinkedNode { ... } // structurally implements INode
class GraphNode { ... } // this also structurally implements INode
int CountNodes(INode start)
{
int i = 0;
for (INode current = start; current != null; current = current.Next)
i++;
return i;
};
void GetCounts()
{
MyLinedNode node1 = BuildLinkedNodes();
GraphNode node2 = BuildGraphNodes();
int count1 = CountNodes(node1);
int count2 = CountNodes(node2);
int count3 = CountNodes("hello world"); // compile fail, as string type structure invalid
}