For Programmers: Free Programming Magazines  


Home > Archive > C# > May 2005 > Self reflection









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Self reflection
Blaze1

2005-05-02, 8:58 pm

I'm writing a base class for out business objects and one requirement
is that the object is able to store a snapshot of it's properties
before editing occurs so that it can revert to them in case of a
cancelled edit.

I thought that I could write a generic SaveState() and RevertState()
function that would use reflection to enumerate the properties and
assign them as needed. The problem is that I'm unsure how to reference
an object type of itself.

For example an implementation might look something like this (non
working code):

private void SaveState()
{
System.Type myType = this.GetType();
myType currState;

PropertyInfo[] props = myType.GetProperties();

foreach (PropertyInfo p in props)
{
currState.Property[p.Name] = thos.Property[p.Name]
}

}

this way, a single base method could be used for all derived classes.

Is this doable? Are there any other methods I could use to implement
this type of functionality?

Bruce Wood

2005-05-02, 8:58 pm

What it looks like you want is a Clone method. Look at the ICloneable
interface.

If you want a good, general way of implementing Clone() that takes
inheritance into account, try this:

// If your type doesn't have a "no arguments" constructor then make a
protected one
// that doesn't do anything, and document the fact that it's for use
only in the Clone()
// method.
protected MyType()
{ }

public MyType Clone()
{
MyType result = new MyType();
this.CopyTo(result);
return result;
}

protected CopyTo(MyType other)
{
// If you're inheriting from another one of your classes that has
// a CopyTo method, then you need to say
// base.CopyTo(other);
// here.
other.field1 = this.field1;
other.field2 = this.field2;
...
}

I wouldn't bother with a generic solution using Reflection. First of
all, Reflection comes with a performance penalty. Second, you'll leave
other programmers scratching their heads... ICloneable is a familiar
idiom that everyone will understand, even if it means writing code in
every class.

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com