我讀了「深入淺出面向對象分析與設計」和我被困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