Esempio n. 1
0
        public static string FormatValue(object v, TypeReference type, List <string> usings)
        {
            if (v == null)
                return "null";

            string ns = type.Namespace;
            usings.AddUsing (ns);

            TypeDefinition tdef = type.ResolveType ();

            string ret;
            if (tdef != null && tdef.IsEnum && tdef.HasFields) {
                Collection <CustomAttribute> attrs = tdef.CustomAttributes;
                CustomAttribute flagsAttr = attrs == null || attrs.Count == 0 ? null : attrs.First ((CustomAttribute attr) => {
                    if (attr.AttributeType.FullName == "System.FlagsAttribute")
                        return true;

                    return false;
                });
                bool flags = flagsAttr != null;
                ns = tdef.Namespace;
                usings.AddUsing (ns);

                string typeName = tdef.FormatName (); //tdef.Name.Replace ("/", ".");
                var sb = new StringBuilder ();
                bool first = true;
                object constant;
                int bits;
                foreach (FieldDefinition fd in tdef.Fields) {
                    if (flags) {
                        constant = fd.Constant;
                        bits = CountBits (constant);
                        if (bits < 0 || bits > 1)
                            continue;

                        if (IsBitSet (v, constant)) {
                            if (first)
                                first = false;
                            else
                                sb.Append (" | ");
                            sb.AppendFormat ("{0}.{1}", typeName, fd.Name);
                        }
                    } else if (v.Equals (fd.Constant)) {
                        sb.AppendFormat ("{0}.{1}", typeName, fd.Name);
                        break;
                    }
                }

                return sb.ToString ();
            }

            ret = v.ToString ();
            if (v is string)
                return "\"" + ret.Replace ("\\", "\\\\") + "\"";

            if (v is bool)
                return ret.ToLower ();

            return ret;
        }