以下代碼按原樣工作,但我想在構造函數 中使用MyProperty類的引用,而不是內聯代碼中的強類型引用。c#將類參數傳遞給構造函數
如何做到這一點,我預計到裁判傳遞給myProperty的,但一切我曾嘗試失敗
我想PropertyClass能夠處理任何myProperty的類即myProperty的任何引用在PropertyClass
如果我錯過了顯而易見的事物,仍然在學習如此抱歉!
任何幫助,非常感謝
薩拉
PropertyClass pc = new PropertyClass(!here!); // Would like to pass MyProperty class here
pc.Settings.Add(new MyProperty("Fred", "Monday"));
pc.SaveXml("MyTest.xml");
public class MyProperty
{
[XmlAttribute]
public string MyPropName { get; set; }
[XmlElement]
public string MyPropData { get; set; }
// default constructor needs to be parameterless for serialisation.
public MyProperty()
{
}
public MyProperty(string Name, string Data)
{
MyPropName = Name;
MyPropData = Data;
}
}
public class PropertyClass
{
public List<MyProperty> Settings { get; set; }
public PropertyClass() // How to pass the required class here ?
{ // public PropertyClass(ref MyProperty myprop)
Settings = new List<MyProperty>();
}
public void SaveXml(string fileName)
{
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
XmlSerializer XML = new XmlSerializer(typeof(List<MyProperty>), new XmlRootAttribute("Settings"));
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
XML.Serialize(stream, Settings, namespaces);
}
}
}
你試圖通過只是你要存儲的對象類型「PropertyClass」的實例?你有沒有嘗試過使用泛型?或者是泛型的序列化問題? –
我想你正在尋找[泛型](https://msdn.microsoft.com/en-us/library/512aeb7t.aspx)?... –
嗨很多感謝回覆 - 我希望有一個密封的類,可以處理傳遞給它的任何'MyProperty'樣式類。 MyProperty類可以包含任意數量的對象,並且提供的類的序列化是核心部分。總之,我只是不希望有一個PropertyClass的所有MyProperty要求,我也需要完全理解爲什麼我試圖做的不工作! –