我正在阅读“面向头对象的设计和分析”,我陷入了第254页。
在下面的Java代码中,我试图将“匹配”方法转换为ac#one。
public class InstrumentSpec {
private Map properties;
public InstrumentSpec(Map properties) {
if (properties == null) {
this.properties = new HashMap();
} else {
this.properties = new HashMap(properties);
}
}
public Object getProperty(String propertyName) {
return properties.get(propertyName);
}
public Map getProperties() {
return properties;
}
public boolean matches(InstrumentSpec otherSpec) {
for (Iterator i = otherSpec.getProperties().keySet().iterator();
i.hasNext(); ) {
String propertyName = (String)i.next();
if (!properties.get(propertyName).equals(
otherSpec.getProperty(propertyName))) {
return false;
}
}
return true;
}
}
这是我到目前为止拥有的C#代码:
public class InstrumentSpec
{
private IDictionary _properties;
public InstrumentSpec(IDictionary properties)
{
this._properties = properties == null ? new Hashtable() : new Hashtable(properties);
}
public object GetProperty(string propertyName)
{
return _properties.Contains(propertyName);
}
public IDictionary Properties
{
get { return _properties; }
set { _properties = value; }
}
public virtual bool Matches(InstrumentSpec otherSpec)
{
foreach (var prop in otherSpec.Properties)
{
if (!prop.Equals(otherSpec.Properties))
{
return false;
}
}
return true;
}
}
任何人都知道如何使Matching方法起作用,以便它检查两个对象是否匹配?
看一下您的比较:
if (!prop.Equals(otherSpec.Properties))
您什么时候期望任何一个“属性”等于包含它的“属性”的集合?Java代码正在与对象的内部“属性”集合进行比较:
if (!properties.get(propertyName).equals(
otherSpec.getProperty(propertyName)))
基本上,这意味着它正在遍历“属性”的集合,并且针对该集合中的每个“属性”,将其与另一个集合中的类似名称的“属性”进行比较。但是您在这里没有引用该对象的集合:
private IDictionary _properties;
您需要将一个集合中的值与另一集合中的值进行比较。如果不检查集合中是否确实存在值(我建议这样做),它可能看起来像这样:
foreach (var prop in otherSpec.Properties.Keys)
{
if (!otherSpec.Properties[prop].Equals(_properties[prop]))
{
return false;
}
}
return true;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句