Cannot access protected member 'object.MemberwiseClone()'

一个人想着一个人 提交于 2019-11-30 07:51:15

问题


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?


回答1:


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(); }
}



回答2:


  • 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;
    }
    



回答3:


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);
    }   
}


来源:https://stackoverflow.com/questions/2023210/cannot-access-protected-member-object-memberwiseclone

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