Cannot access protected member 'object.MemberwiseClone()'

后端 未结 3 1485
太阳男子
太阳男子 2020-12-15 16:52

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

Cannot access protected member \'object.Memberwise         


        
相关标签:
3条回答
  • 2020-12-15 17:31

    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);
        }   
    }
    
    0 讨论(0)
  • 2020-12-15 17:44
    • 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;
      }
      
    0 讨论(0)
  • 2020-12-15 17:49

    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(); }
    }
    
    0 讨论(0)
提交回复
热议问题