private static void AppendField(SwitchModel model, MemberInfo mi) { if (mi.GetAttr <SwitchAttribute>() != null) { // switch field if (model.SwitchField != null) { throw new InvalidOperationException("duplicate switch attribute"); } model.SwitchField = new FieldDesc(mi); foreach (var cAttr in mi.GetAttrs <CaseAttribute>()) { if (model.Branches.ContainsKey(cAttr.Value)) { throw new InvalidOperationException("duplicate case value " + cAttr.Value.ToString()); } model.Branches.Add(cAttr.Value, null); } } else { // case field foreach (var cAttr in mi.GetAttrs <CaseAttribute>()) { if (model.Branches.ContainsKey(cAttr.Value)) { throw new InvalidOperationException("duplicate case value " + cAttr.Value.ToString()); } model.Branches.Add(cAttr.Value, new FieldDesc(mi)); } } }
public static Delegate EmitWriter(Type targetType) { OrderModel ordModel = OrderModel.Create(targetType); SwitchModel swModel = SwitchModel.Create(targetType); if (swModel != null && ordModel != null) { throw new InvalidOperationException("unknown way to convert"); } if (swModel != null) { return(swModel.BuildWriter(targetType)); } if (ordModel != null) { return(ordModel.BuildWriter(targetType)); } return(null); }
public static SwitchModel Create(Type t) { SwitchModel model = new SwitchModel(); model.Branches = new Dictionary <object, FieldDesc>(); foreach (var fi in t.GetFields().Where((fi) => fi.IsPublic && !fi.IsStatic)) { AppendField(model, fi); } foreach (var pi in t.GetProperties().Where((pi) => pi.CanWrite && pi.CanRead)) { AppendField(model, pi); } if (model.SwitchField == null && model.Branches.Count == 0) { return(null); } if (model.SwitchField == null) { throw new InvalidOperationException("switch attribute not found"); } if (model.Branches.Count <= 1) { throw new InvalidOperationException("requires more than two case attributes"); } if (model.Branches.Values.All((f) => f == null)) { throw new InvalidOperationException("required no void case attribute"); } return(model); }