简体   繁体   中英

Can you change the value of the Name property of a Type at runtime?

Is it possible to change/override the Name property of a Type?

Given the class definition:

class Sample
{}

Can you change the value that typeof(Sample).Name returns?

I'm using an custom serialization library, which literally use typeof(T).Name in their source code:

writer.WriteStartElement(typeof(T).Name);
writer.WriteValue(item);
writer.WriteEndElement();

No, you cannot change the .Name of a Type at runtime. However, most serialization libraries allow you to have some control of the processing of names, either by providing a custom "binder" (etc), or by annotating the type with attributes to indicate the preferred name to use (note: most libraries that allow attributes also allow the name to be provided via runtime configuration of the serialization library).

An important question, then, is: what is the serialization library that is being used here?

If the serialization library doesn't support this, and cannot be changed, then the only alternative (short of renaming Sample ) to all of this is to create a type (either by hand, or via TypeBuilder at runtime) that looks like the original type, but with a different code, and similarly: create code that translates between the two types.

I don't know any way to accomplish such a task. CLR does similar thing with marshalled by ref objects, but I doubt that it will allow you to "rename" your class or its property(field) in such a way.

Your best bet is to either conform to the old code or(the better one)is to replace or change the serialization routines to be less rigid.

As for XML serialization using the XmlSerialization library in the BCL, you can override the xml Element name to be generated using the following attribute:

[XmlElement("SomeOtherName")]
public class Sample{...}

From your question, you mentioned you want to control the name during serialize

If you want to change the name during the serialization, you can use the following attributes

[DataContract(Name = "NewName")] 
[XmlRoot("NewName")] 
class Sample
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM