Cannot access protected member 'object.MemberwiseClone()'

后端 未结 3 1500
太阳男子
太阳男子 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: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:

      /// 
      /// Clones a object via shallow copy
      /// 
      /// Object Type to Clone
      /// Object to Clone
      /// New Object reference
      public static T CloneObject(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;
      }
      

提交回复
热议问题