Cannot access protected member 'object.MemberwiseClone()'

亡梦爱人 提交于 2019-11-29 05:32: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(); }
}
  • 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;
    }
    

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);
    }   
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!