Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access protected member 'object.MemberwiseClone()'

Tags:

c#

clone

I'm trying to use .MemberwiseClone() on a custom class of mine, but it throws up this error:

Cannot access protected member 'object.MemberwiseClone()' via a qualifier of type 'BLBGameBase_V2.Enemy'; the qualifier must be of type 'BLBGameBase_V2.GameBase' (or derived from it) 

What does this mean? Or better yet, how can I clone an Enemy class?

like image 384
Xenoprimate Avatar asked Jan 07 '10 19:01

Xenoprimate


2 Answers

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(); } } 
like image 106
SLaks Avatar answered Sep 21 '22 08:09

SLaks


  • you can´t use MemberwiseClone() directly, you must implement it via derived class (recomended)
  • but, via reflection, you can cheat it :)
  • 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; } 
like image 37
ModMa Avatar answered Sep 20 '22 08:09

ModMa