public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string s && GetEntityReferenceType(context) is Type erefType) { var tail = s.IndexOf('('); if (tail >= 0) { s = s.Substring(0, tail); } s = s.Trim(); if (int.TryParse(s, out var n)) { return(Activator.CreateInstance(erefType, n)); } var game = GetGame(context); if (game != null) { var entityType = erefType.GenericTypeArguments[0]; var entities = game.Entities.GetEntities(entityType).OfType <IHasId>(); var entity = entities.FirstOrDefault(ent => ent.Id == s); if (entity == null) { throw new IndexOutOfRangeException( $"There is no {FriendlyNames.Singular(entityType)} with ID '{s}'"); } return(Activator.CreateInstance(erefType, entity)); } } return(base.ConvertFrom(context, culture, value)); }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType != typeof(string)) { return(base.ConvertTo(context, culture, value, destinationType)); } switch (value) { case IHasId hasId: return(hasId.Id); case EntityDefinition def: return(FriendlyNames.Singular(def.EntityType) + " definition #" + def.Index); default: return(null); } }