Paul E Collins wrote:
<da********@gmail.com> wrote:
...or, to put it perhaps more communicative, something like this:
Type someObjectsType = someObject.GetType();
someObjectsType newObject = new someObjectsType();
You can use Activator.CreateInstance to create an object from its
type.
Eq.
Hi Paul :)
Thanks for your reply. Actually, I think I was a bit too generic in my
question. What's really happening is this... Consider these two
(simplified) classes:
public abstract class BaseClass
{
// A yet undefined item collection that can be of type
// "AppointmentCollection", "TaskCollection", or
// "ContactCollection", depending on what derived class
// is instantiated (PimItemCollection is the base type
// for all these):
protected PimItemCollection itemCollection;
public BaseClass(PimItemCollection itemCollection)
{
this.itemCollection = itemCollection;
}
}
public class TasksClass : BaseClass
{
// This derived class is supposed to handle tasks,
// so it passes a ref to a TaskCollection to the
// base class.
public TasksClass()
: base(new OutlookSession().Tasks.Items)
{
}
}
Okay, so one thing that the base class should be able to do, is provide
a "backup" (xml serialization) functionality of the items in a
TaskCollection, ContactCollection, or AppointmentCollection (which
contain objects of type PimItem : Task, PimItem : Contact, PimItem :
Appointment, respectively), without knowing the specific type up front.
Pulling out items as PimItem objects from the itemCollection works
fine, and I can create xml output from this without problem. But when I
need to restore, it's another deal. Perhaps because of widening casts
vs. narrowing casts?
Anyway, what I was hoping would work was the following. It's code
that's supposed to be in the base class:
// Detect the type of the items in the backup provider's
itemCollection:
System.Type itemType = itemCollection[0].GetType();
// Read backed up data into a new array:
XmlSerializer xmlSerializer = new
XmlSerializer(typeof(itemType[]));
StreamReader streamReader = new StreamReader(backupFile);
XmlTextReader xmlTextReader = new
XmlTextReader(streamReader);
itemType[] pimItems =
(itemType[])xmlSerializer.Deserialize(xmlTextReader);
xmlTextReader.Close();
streamReader.Close();
File.Delete(backupFile);
Here, I get a lot of errors saying, "The type or namespace name
'itemType' could not be found (are you missing a using directive or an
assembly reference?)"
So, basically, I don't really need to create a new object of the
unknown type, but I need to be able to use it like I'm stabbing at
above... Any ideas of how I could do something like that?
Thanks again,
Daniel :)