Due to the question here is marked as duplicated, so here I repeat the question and make more explanation about the question. Hope someone can give some suggestions. =======================================
As described in the question, here is a enum:
public enum MyEnum { One, Two, Three}
is going to be parsed based on mutl strings.For example, below strings are all going to be parsed as MyEnum.Two:
"Two", "TWO", "Second", "2"
The reason that I can't leverage the description attributes or a mapping dictionary directly is that the mapping strings come from an external xml file. The mapping will change after a period of time and so that It's not possible just adding the description attribute with the above declared enum.
For example, the mappings above was build one month ago and now there are some extra items required as below and these new items will be just add to the xml file:
"2nd", "The Second one"
Furthermore, I use a self developed script engine to parse above and other similar needs (that's why I don't use a simple mapping function) :
Object x = engine.Execute( /*some script codes defined in external xml*/ );
if (ReturnType.IsEnum && Enum.IsDefined(ReturnType, x)) //ReturnType is defined in external xml file
return Enum.Parse(ReturnType, x.ToString());
else if (ReturnType.IsEnum)
{
// Hope I can handle Extra mapping here
}
else
return Convert.ChangeType(x, ReturnType);
It seems very strange to just pass-in a mapping table to the above codes because it was designed for generic script executing purpose. So I think @xanatos (in the prevous 'duplicated' question) gave a way to resolve this issue, but the mapping (via customized attributes) should be generated at runtime. Attributes seems a meta data and can't be changed after compilation, however, I found some posts say that I can use TypeDescriptor to add attributes at runtime, is it possible? and How?