以下代码按原样工作,但我想在构造函数 中使用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要求,我也需要完全理解为什么我试图做的不工作! –