我怎样才能使这段代码更通用
我怎样才能使这段代码更加通用,因为字典键可以是不同的类型,具体取决于库的用户想要实现的内容?例如,在 Node 的“唯一键”实际上是“int”而不是“string”的情况下,有人可能会使用扩展方法/接口。
public interface ITopology
{
Dictionary<string, INode> Nodes { get; set; }
}
public static class TopologyExtns
{
public static void AddNode(this ITopology topIf, INode node)
{
topIf.Nodes.Add(node.Name, node);
}
public static INode FindNode(this ITopology topIf, string searchStr)
{
return topIf.Nodes[searchStr];
}
}
public class TopologyImp : ITopology
{
public Dictionary<string, INode> Nodes { get; set; }
public TopologyImp()
{
Nodes = new Dictionary<string, INode>();
}
}
How could I make this code more generic in the sense that the Dictionary key could be a different type, depending on what the user of the library wanted to implement? For example someone might what to use the extension methods/interfaces in a case where there "unique key" so to speak for Node is actually an "int" not a "string" for example.
public interface ITopology
{
Dictionary<string, INode> Nodes { get; set; }
}
public static class TopologyExtns
{
public static void AddNode(this ITopology topIf, INode node)
{
topIf.Nodes.Add(node.Name, node);
}
public static INode FindNode(this ITopology topIf, string searchStr)
{
return topIf.Nodes[searchStr];
}
}
public class TopologyImp : ITopology
{
public Dictionary<string, INode> Nodes { get; set; }
public TopologyImp()
{
Nodes = new Dictionary<string, INode>();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使接口通用,然后使用
Func
作为键的选择器。这假设您希望从节点中提取字典的键。如果这不是硬性要求,那么您可以使用签名中的通用类型说明符来指定密钥本身。您还可以考虑将 INode 设为泛型类型。这将允许您将 Key 指定为通用类型的属性,该实现可以遵循适当的“真实”键。这将使您不必为扩展方法提供键或选择器。
替代方案:
用作:
Make the interface generic, then use a
Func<INode,T>
as a selector for the key. This assumes that you want the key for the dictionary to be extracted from the node. If this isn't a hard requirement, then you could specify the key itself using the generic type specifier in the signature.You might also consider making INode a generic type. That would allow you to specify the Key as a property of the generic type which the implementation could defer to the appropriate "real" key. This would save you from having to supply either the key or a selector for the extension method.
Alternative:
Used as:
为什么不让你的拓扑接口变得通用呢?我自己对扩展方法有点模糊,但这应该是可行的。
Why not make your Topology Interface generic? I'm a little fuzzy on the extension methods myself, but this should be workable.