Skip to content

Instantly share code, notes, and snippets.

@follesoe
Created December 24, 2010 14:27
Show Gist options
  • Select an option

  • Save follesoe/754277 to your computer and use it in GitHub Desktop.

Select an option

Save follesoe/754277 to your computer and use it in GitHub Desktop.
Play with reflection and you might get burned...
using System;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
namespace ReflectionTest
{
public class BaseEntity : ICloneable
{
public object Clone()
{
object newObject = Activator.CreateInstance(this.GetType());
FieldInfo[] newFields = newObject.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo[] oldFields = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
for (int i = 0; i < oldFields.Length; ++i)
{
newFields[i].SetValue(newObject, oldFields[i].GetValue(this));
}
return newObject;
}
}
public class PersonEntity : BaseEntity
{
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public override string ToString()
{
return string.Format("{0}, {1} years old", name, age);
}
public PersonEntity QuickClone()
{
PersonEntity newPerson = new PersonEntity();
newPerson.age = this.age;
newPerson.name = this.name;
return newPerson;
}
}
public class Program
{
static void Main(string[] args)
{
PersonEntity person = new PersonEntity();
person.Age = 20;
person.Name = "Jonas Follesø";
Console.WriteLine("Starting to clone...");
for (int i = 0; i < 250000; ++i)
{
person.Clone();
person.QuickClone();
}
Console.WriteLine("Done cloning...");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment