我读了“深入浅出面向对象分析与设计”和我被困254页将Java代码转换为C#代码
在下面的Java代码上,我试图转换的“匹配”的方法到ac#之一。
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;
}
}
任何人有任何想法如何使匹配方法工作,以便检查是否两个对象相匹配?
心不是有一个.equals()为每个对象? – 2014-09-01 11:46:47
yes在每个对象上都有一个equals()方法,正如你所看到的,我已经在我的代码中使用了它,但是我似乎无法用IDictionary来正确使用它。 – 2014-09-01 11:50:36