I\'m trying to use .MemberwiseClone()
on a custom class of mine, but it throws up this error:
Cannot access protected member \'object.Memberwise
here is an extension method that allows the cloning of any object (use with the caveat that it not work in all cases)
public static class Extra_Objects_ExtensionMethods
{
public static T clone<T>(this T objectToClone)
{
try
{
if (objectToClone.isNull())
"[object<T>.clone] provided object was null (type = {0})".error(typeof(T));
else
return (T)objectToClone.invoke("MemberwiseClone");
}
catch(Exception ex)
{
"[object<T>.clone]Faild to clone object {0} of type {1}".error(objectToClone.str(), typeof(T));
}
return default(T);
}
}
you can use this litle extension for the classes that not implement ICloneable:
/// <summary>
/// Clones a object via shallow copy
/// </summary>
/// <typeparam name="T">Object Type to Clone</typeparam>
/// <param name="obj">Object to Clone</param>
/// <returns>New Object reference</returns>
public static T CloneObject<T>(this T obj) where T : class
{
if (obj == null) return null;
System.Reflection.MethodInfo inst = obj.GetType().GetMethod("MemberwiseClone",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (inst != null)
return (T)inst.Invoke(obj, null);
else
return null;
}
Within any class X
, you can only call MemberwiseClone
(or any other protected method) on an instance of X
. (Or a class derived from X
)
Since the Enemy
class that you're trying to clone doesn't inherit the GameBase
class that you're trying to clone it in, you're getting this error.
To fix this, add a public Clone
method to Enemy
, like this:
class Enemy : ICloneable {
//...
public Enemy Clone() { return (Enemy)this.MemberwiseClone(); }
object ICloneable.Clone() { return Clone(); }
}