The String.MemberwiseClone () method called by reflection does not work, why?

Let me say that I know that this is a protected method, and I should not call it, but should not work, since MemberwiseClone is defined in Object and String inherits from it?

So, this is a cloning method (I removed the zero link processing to focus on what's important):

public static T ShallowClone<T>(T obj)
{
    MethodInfo memberwiseClone;
    memberwiseClone = obj.GetType().GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
    return (T)memberwiseClone.Invoke(obj, null);
}

And if I call it like this:

string str = ShallowClone("My string");

The resulting string (str) will be:

"M\0\0\0\0\0\0\0\0"

Thanks in advance!

+3
source share
1 answer

, . , String.MemberwiseClone , . , , , .

, , , : , , , , , .

+2

All Articles