object - c# passing class argument to constructor -
the following codes works is, use reference myproperty class passed in constructor instead of typed references in inline code.
how do this, expected pass ref myproperty have tried fails
i propertyclass able handle myproperty classes i.e. no references myproperty in propertyclass
still learning sorry if have missed obvious !
many help
sarah
propertyclass pc = new propertyclass(!here!); // 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 parameterless 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 pass 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); } } }
i change definition of propertyclass
to
public class propertyclass<t> { public list<t> settings { get; set; } public propertyclass() { settings = new list<t>(); } public void savexml(string filename) { using (filestream stream = new filestream(filename, filemode.create)) { xmlserializer xml = new xmlserializer(typeof(list<t>), new xmlrootattribute("settings")); xmlserializernamespaces namespaces = new xmlserializernamespaces(); namespaces.add(string.empty, string.empty); xml.serialize(stream, settings, namespaces); } } }
the type parameter t
specifies type of items in list<t>
, can instantiate propertyclass
follows
var pc = new propertyclass<myproperty>();
or when tired of myproperty
can change new propertyclass<foo>()
without changing elsewhere.
another nice feature generics can place constraints on type parameter in line declare like:
public class propertyclass<t> t : myclass, imyinterface, new()
this means t
has derived myclass
, has implement imyinterface
, has have parameterless constructor. (obviously not need add such constraints, can useful in cases).
i want rant little more, sure can play , find uses it.
Comments
Post a Comment