protected static object CreateNewInstance(System.Type type) { object obj2 = new Object(); try { if (type.IsArray) { return Array.CreateInstance(type.GetElementType(), 1); } if (type == typeof(string)) { return ""; } if (type == typeof(Guid)) { return Guid.NewGuid(); } if (type == typeof(XmlElement)) { XmlDocument document = new XmlDocument(); return document.CreateElement("MyElement"); } if (type == typeof(XmlAttribute)) { XmlDocument document2 = new XmlDocument(); return document2.CreateAttribute("MyAttribute"); } obj2 = Activator.CreateInstance(type); } catch { } return obj2; }
private static System.Type FindIEnumerable(System.Type seqType) { if (seqType == null || seqType == typeof(string)) return null; if (seqType.IsArray) return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); if (seqType.IsGenericType) { foreach (System.Type arg in seqType.GetGenericArguments()) { System.Type ienum = typeof(IEnumerable<>).MakeGenericType(arg); if (ienum.IsAssignableFrom(seqType)) { return ienum; } } } System.Type[] ifaces = seqType.GetInterfaces(); if (ifaces != null && ifaces.Length > 0) { foreach (System.Type iface in ifaces) { System.Type ienum = FindIEnumerable(iface); if (ienum != null) return ienum; } } if (seqType.BaseType != null && seqType.BaseType != typeof(object)) { return FindIEnumerable(seqType.BaseType); } return null; }
private static System.Type GetArrayOrListElementType(System.Type listType) { if (listType.IsArray) { return listType.GetElementType(); } if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(List<>)) { return listType.GetGenericArguments()[0]; } return null; }
/// <summary> /// Determines whether this instance [can convert to] the specified type. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if this instance [can convert to] the specified type; otherwise, <c>false</c>. /// </returns> public static bool CanConvertTo(System.Type type) { if (type.IsArray) { type = type.GetElementType(); } if (TypeDescriptor.GetConverter(type).CanConvertFrom(typeof(string))) { return true; } MethodInfo info = null; return methods.TryGetValue(type, out info); }
internal static string Type(System.Type type, bool dropNamespaces = false) { string assemblyQualifiedName; Exception exception; if (type == null) { return string.Empty; } if (type.IsGenericType && !type.IsGenericTypeDefinition) { string str2 = Type(type.GetGenericTypeDefinition(), dropNamespaces); int num = str2.LastIndexOf('`'); int length = str2.Length - (str2.Length - num); StringBuilder builder = new StringBuilder(str2, 0, length, 0x200); builder.Append('['); bool flag = true; foreach (System.Type type2 in type.GetGenericArguments()) { if (!flag) { builder.Append(','); } flag = false; builder.Append(Type(type2, dropNamespaces)); } builder.Append(']'); assemblyQualifiedName = builder.ToString(); } else if (type.IsArray) { string str3 = Type(type.GetElementType(), dropNamespaces); StringBuilder builder2 = new StringBuilder(str3, str3.Length + 10); builder2.Append("["); for (int i = 0; i < (type.GetArrayRank() - 1); i++) { builder2.Append(","); } builder2.Append("]"); assemblyQualifiedName = builder2.ToString(); } else { assemblyQualifiedName = TypeAccelerators.FindBuiltinAccelerator(type) ?? (dropNamespaces ? type.Name : type.ToString()); } if ((!type.IsGenericParameter && !type.ContainsGenericParameters) && (!dropNamespaces && (LanguagePrimitives.ConvertStringToType(assemblyQualifiedName, out exception) != type))) { assemblyQualifiedName = type.AssemblyQualifiedName; } return assemblyQualifiedName; }
/// <summary> /// Converts to type. /// </summary> /// <param name="Params">The params.</param> /// <param name="ParamIndex">Index of the param.</param> /// <param name="toType">To type.</param> /// <param name="ConvertedParam">The converted param.</param> /// <returns></returns> public static bool ConvertToType(object[] Params, ref int ParamIndex, System.Type toType, out object ConvertedParam) { ConvertedParam = null; if (ParamIndex < Params.Length) { if (Params[ParamIndex] is string) { bool flag2 = false; try { ConvertedParam = TypeDescriptor.GetConverter(toType).ConvertFromString((string) Params[ParamIndex]); ParamIndex++; flag2 = true; } catch (Exception) { } return flag2; } if (toType.IsArray && (Params[ParamIndex] is object[])) { object[] @params = (object[]) Params[ParamIndex]; object[] objArray2 = (object[]) Array.CreateInstance(toType.GetElementType(), @params.Length); int paramIndex = 0; while (paramIndex < @params.Length) { int index = paramIndex; object convertedParam = null; if (!ConvertToType(@params, ref paramIndex, toType.GetElementType(), out convertedParam)) { break; } objArray2[index] = convertedParam; } if (paramIndex == @params.Length) { ConvertedParam = objArray2; ParamIndex++; return true; } } try { MethodInfo info = null; if (methods.TryGetValue(toType, out info)) { ConvertedParam = null; object[] parameters = new object[] { Params, (int) ParamIndex, ConvertedParam }; if ((bool) info.Invoke(null, parameters)) { ParamIndex = (int) parameters[1]; ConvertedParam = parameters[2]; return true; } } } catch (Exception) { } } return false; }
public static string GetNiceTypeName(System.Type type, NamingOptions options) { if (options != null && options.NameOverrideFunc !=null) { string s = options.NameOverrideFunc(type); if (s != null) { return s; } } if (IsNullableType(type)) { var actualtype = type.GetGenericArguments()[0]; return GetNiceTypeName(actualtype, options) + "?"; } if (type.IsArray) { var at = type.GetElementType(); return string.Format("{0}[]", GetNiceTypeName(at, options)); } if (type.IsGenericType) { var sb = new System.Text.StringBuilder(); var tokens = type.Name.Split('`'); sb.Append(tokens[0]); var gas = type.GetGenericArguments(); var ga_names = gas.Select(i => GetNiceTypeName(i, options)); sb.Append("<"); Join(sb, ", ", ga_names); sb.Append(">"); return sb.ToString(); } return type.Name; }
public object deserialize(System.Type lPropertyType, object lTableValue) { object lValue = null; if ( lPropertyType.IsSubclassOf(typeof(System.Array)) && lTableValue is ArrayList) { var lTableArrayList = (ArrayList)lTableValue; var lElementType = lPropertyType.GetElementType(); lValue = System.Array.CreateInstance(lElementType, lTableArrayList.Count); var lArray = (System.Array)lValue; int i = 0; foreach (var lTableValueElement in lTableArrayList) { var lElement = System.Activator.CreateInstance(lElementType); _serializeObject.serializeFromTable(lElement, (Hashtable)lTableValueElement); lArray.SetValue(lElement, i); ++i; } } else if (lTableValue.GetType() == typeof(Hashtable)) { lValue = System.Activator.CreateInstance(lPropertyType); _serializeObject.serializeFromTable(lValue, (Hashtable)lTableValue); } return lValue; }
public static compiled_type_node get_type_node(System.Type st) { //(ssyy) Обрабатываем параметры generic-типов //Сделаю потом, если это понадобится. //if (st.IsGenericParameter) //{ //} //if (st.Name.EndsWith("&") == true) //(ssyy) Лучше так if (st.IsByRef) { //return get_type_node(st.Module.GetType(st.FullName.Substring(0,st.FullName.Length-1))); return get_type_node(st.GetElementType()); } compiled_type_node ctn;//=compiled_types[st]; if (compiled_types.TryGetValue(st, out ctn)) { //ctn.reinit_scope(); return ctn; } ctn=new compiled_type_node(st); //Если это не чистить, будет ошибка. Т.к. при следующей компиляции области видимости могут изменится. //Но если это чистить то тоже ошибка. нужна еще одна статическая таблица для стандартных типов compiled_types[st] = ctn; ctn.init_constructors(); ctn.mark_if_delegate(); ctn.mark_if_array(); if (st.IsEnum) { internal_interface ii = SystemLibrary.SystemLibrary.integer_type.get_internal_interface(internal_interface_kind.ordinal_interface); ordinal_type_interface oti_old = (ordinal_type_interface)ii; enum_const_node lower_value = new enum_const_node(0, ctn, ctn.loc); enum_const_node upper_value = new enum_const_node(st.GetFields().Length-2, ctn, ctn.loc); ordinal_type_interface oti_new = new ordinal_type_interface(oti_old.inc_method, oti_old.dec_method, oti_old.inc_value_method, oti_old.dec_value_method, oti_old.lower_eq_method, oti_old.greater_eq_method, oti_old.lower_method, oti_old.greater_method, lower_value, upper_value, oti_old.value_to_int, oti_old.ordinal_type_to_int); ctn.add_internal_interface(oti_new); SystemLibrary.SystemLibrary.make_binary_operator(compiler_string_consts.gr_name, ctn, SemanticTree.basic_function_type.enumgr, SystemLibrary.SystemLibrary.bool_type); SystemLibrary.SystemLibrary.make_binary_operator(compiler_string_consts.greq_name, ctn, SemanticTree.basic_function_type.enumgreq, SystemLibrary.SystemLibrary.bool_type); SystemLibrary.SystemLibrary.make_binary_operator(compiler_string_consts.sm_name, ctn, SemanticTree.basic_function_type.enumsm, SystemLibrary.SystemLibrary.bool_type); SystemLibrary.SystemLibrary.make_binary_operator(compiler_string_consts.smeq_name, ctn, SemanticTree.basic_function_type.enumsmeq, SystemLibrary.SystemLibrary.bool_type); InitEnumOperations(ctn); } //ctn.init_scope(); //TODO: Тут надо подумать. Может как-то сделать по другому? if (!NetHelper.NetHelper.IsStandType(st)) { SystemLibrary.SystemLibrary.init_reference_type(ctn); } return ctn; }
protected void OutputHaskellType(System.Text.StringBuilder sb, System.Type ty, System.Int32 idx) { /* Curiously, &-versions of prim types are showing up (cf. System.Uri.HexUnescape). * Just ignore them. */ if (ty.FullName == "System.Boolean" || ty.FullName == "System.Boolean&" ) { sb.Append("Bool"); return; } if (ty.FullName == "System.String") { sb.Append("String"); return; } if (ty.FullName == "System.Char" || ty.FullName == "System.Char&") { sb.Append("Char"); return; } if (ty.FullName == "System.Double" || ty.FullName == "System.Double&") { sb.Append("Double"); return; } if (ty.FullName == "System.Single" || ty.FullName == "System.Single&") { sb.Append("Double"); return; } if (ty.FullName == "System.SByte" || ty.FullName == "System.SByte&") { AddImport("Data.Int"); sb.Append("Data.Int.Int8"); return; } if (ty.FullName == "System.Int16" || ty.FullName == "System.Int16&") { AddImport("Data.Int"); sb.Append("Data.Int.Int16"); return; } if (ty.FullName == "System.Int32" || ty.FullName == "System.Int32&") { sb.Append("Int"); return; } if (ty.FullName == "System.Int64" || ty.FullName == "System.Int64&") { AddImport("Data.Int"); sb.Append("Data.Int.Int64"); return; } if (ty.FullName == "System.Byte" || ty.FullName == "System.Byte&") { AddImport("Data.Word"); sb.Append("Data.Word.Word8"); return; } if (ty.FullName == "System.UInt16" || ty.FullName == "System.UInt16&") { AddImport("Data.Word"); sb.Append("Data.Word.Word16"); return; } if (ty.FullName == "System.UInt32" || ty.FullName == "System.UInt32&") { AddImport("Data.Word"); sb.Append("Data.Word.Word32"); return; } if (ty.FullName == "System.UInt64" || ty.FullName == "System.UInt64&") { AddImport("Data.Word"); sb.Append("Data.Word.Word64"); return; } if (ty.FullName == "System.Void") { sb.Append("()"); return; } if (ty.FullName == "System.Object") { AddImport("Dotnet.System.Object"); sb.AppendFormat("Dotnet.System.Object.Object a{0}",idx); return; } if (ty.IsArray) { AddImport("Dotnet.System.Array"); sb.Append("Dotnet.System.Array.Array ("); OutputHaskellType(sb, ty.GetElementType(), idx); sb.Append(")"); } else { AddImport("Dotnet." + ty.FullName); sb.AppendFormat("Dotnet.{0}.{1} a{2}", ty.FullName, ty.Name, idx); } }
public static void SetParameter(object umlType, System.Type systemType, AssemblyImporter importer) { while (systemType.HasElementType)//Removing &, *, and [] { if (systemType.IsByRef || systemType.IsPointer) { Uml2.Parameter parameter = umlType as Uml2.Parameter; if (parameter != null) { parameter.Direction = ExpertCoder.Uml2.ParameterDirectionKind.inout; } } if (systemType.IsArray) { Uml2.MultiplicityElement array = umlType as Uml2.MultiplicityElement; if (array != null) { array.Lower = 0; array.Upper = Uml2.UnlimitedNatural.Infinity; } } systemType = systemType.GetElementType (); } AssemblyType assemblyType = AssemblyHelper.CreateAssemblyType (importer, systemType); Uml2.TypedElement umlTyped = umlType as Uml2.TypedElement; if (umlTyped != null && assemblyType != null) { umlTyped.Type = assemblyType.UmlType; } }
public static FieldType getTypeCode(System.Type c) { FieldType type; if (c.Equals(typeof(byte))) { type = FieldType.tpByte; } else if (c.Equals(typeof(sbyte))) { type = FieldType.tpSByte; } else if (c.Equals(typeof(short))) { type = FieldType.tpShort; } else if (c.Equals(typeof(ushort))) { type = FieldType.tpUShort; } else if (c.Equals(typeof(char))) { type = FieldType.tpChar; } else if (c.Equals(typeof(int))) { type = FieldType.tpInt; } else if (c.Equals(typeof(uint))) { type = FieldType.tpUInt; } else if (c.Equals(typeof(long))) { type = FieldType.tpLong; } else if (c.Equals(typeof(ulong))) { type = FieldType.tpULong; } else if (c.Equals(typeof(float))) { type = FieldType.tpFloat; } else if (c.Equals(typeof(double))) { type = FieldType.tpDouble; } else if (c.Equals(typeof(System.String))) { type = FieldType.tpString; } else if (c.Equals(typeof(bool))) { type = FieldType.tpBoolean; } else if (c.Equals(typeof(System.DateTime))) { type = FieldType.tpDate; } else if (c.IsEnum) { type = FieldType.tpEnum; } else if (c.Equals(typeof(decimal))) { type = FieldType.tpDecimal; } else if (c.Equals(typeof(Guid))) { type = FieldType.tpGuid; } else if (typeof(IPersistent).IsAssignableFrom(c)) { type = FieldType.tpObject; } else if (typeof(ValueType).IsAssignableFrom(c)) { type = FieldType.tpValue; } else if (typeof(IGenericPArray).IsAssignableFrom(c)) { type = FieldType.tpArrayOfOid; } else if (typeof(IGenericLink).IsAssignableFrom(c)) { type = FieldType.tpLink; } else if (c.IsArray) { type = getTypeCode(c.GetElementType()); if ((int)type >= (int)FieldType.tpLink) { throw new DatabaseException(DatabaseException.ErrorCode.UNSUPPORTED_TYPE, c); } type = (FieldType)((int)type + (int)FieldType.tpArrayOfBoolean); } else { type = FieldType.tpRaw; } return type; }
protected System.Type[] GetIncludedTypes(System.Type type) { ArrayList list = new ArrayList(); list.Add(type); if (type.IsByRef) { type = type.GetElementType(); } MethodInfo currentMethod = this.GetCurrentMethod(); if (currentMethod != null) { this.AddTypeToList(GetAllIncludedTypes(currentMethod.DeclaringType), list); } this.AddTypeToList(GetAllIncludedTypes(type), list); return (System.Type[])list.ToArray(typeof(System.Type)); }
public object MapToIdlSequence(System.Type clsType, int bound, AttributeExtCollection allAttributes, AttributeExtCollection elemTypeAttributes) { Type serializerType = typeof(IdlSequenceSerializer<>).MakeGenericType(clsType.GetElementType()); ConstructorInfo ci = serializerType.GetConstructor(new Type[] { AttributeExtCollection.ClassType, ReflectionHelper.Int32Type, ReflectionHelper.BooleanType, SerializerFactory.ClassType }); return ci.Invoke(new object[] { elemTypeAttributes, bound, m_config.SequenceSerializationAllowNull, this }); }
internal static string TypeName(System.Type type, bool bEmbedded, WsdlGenerator.XMLNamespace thisxns) { string str = null; if (type.IsArray) { return ProcessArray(type, thisxns); } string str2 = WsdlGenerator.RefName(type); System.Type elementType = type; if (type.IsByRef) { elementType = type.GetElementType(); str2 = WsdlGenerator.RefName(elementType); if (elementType.IsArray) { return ProcessArray(elementType, thisxns); } } str = SudsConverter.MapClrTypeToXsdType(elementType); if (str != null) { return str; } string ns = type.Namespace; Assembly assem = type.Module.Assembly; WsdlGenerator.XMLNamespace xns = null; xns = (WsdlGenerator.XMLNamespace) thisxns.Generator._typeToInteropNS[type]; if (xns == null) { xns = thisxns.LookupSchemaNamespace(ns, assem); if (xns == null) { xns = thisxns.Generator.LookupNamespace(ns, assem); if (xns == null) { xns = thisxns.Generator.AddNamespace(ns, assem); } thisxns.DependsOnSchemaNS(xns, false); } } StringBuilder builder = new StringBuilder(0x100); builder.Append(xns.Prefix); builder.Append(':'); builder.Append(str2); return builder.ToString(); }
private static string ProcessArray(System.Type type, WsdlGenerator.XMLNamespace xns) { string wireQname = null; bool flag = false; System.Type elementType = type.GetElementType(); string str2 = "ArrayOf"; while (elementType.IsArray) { str2 = str2 + "ArrayOf"; elementType = elementType.GetElementType(); } wireQname = TypeName(elementType, true, xns); int index = wireQname.IndexOf(":"); wireQname.Substring(0, index); string str3 = wireQname.Substring(index + 1); int arrayRank = type.GetArrayRank(); string str4 = ""; if (arrayRank > 1) { str4 = arrayRank.ToString(CultureInfo.InvariantCulture); } string name = (str2 + str3.Substring(0, 1).ToUpper(CultureInfo.InvariantCulture) + str3.Substring(1) + str4).Replace('+', 'N'); if (xns.LookupArraySchemaType(name) == null) { WsdlGenerator.ArraySchemaType asType = new WsdlGenerator.ArraySchemaType(type, name, SchemaBlockType.ComplexContent, false); WsdlGenerator.Restriction particle = new WsdlGenerator.Restriction(); WsdlGenerator.SchemaAttribute attribute = new WsdlGenerator.SchemaAttribute(); if (flag) { attribute.AddArray(wireQname); } else { string str6 = type.Name; index = str6.IndexOf("["); attribute.AddArray(wireQname + str6.Substring(index)); } particle.AddArray(attribute); asType.AddParticle(particle); xns.AddArraySchemaType(asType); } return (xns.Prefix + ":" + name); }
private Type ImportImpl(System.Type type) { if (type.Assembly == typeof(IKVM.Reflection.Type).Assembly) { throw new ArgumentException("Did you really want to import " + type.FullName + "?"); } if (type.HasElementType) { if (type.IsArray) { if (type.Name.EndsWith("[]")) { return Import(type.GetElementType()).MakeArrayType(); } else { return Import(type.GetElementType()).MakeArrayType(type.GetArrayRank()); } } else if (type.IsByRef) { return Import(type.GetElementType()).MakeByRefType(); } else if (type.IsPointer) { return Import(type.GetElementType()).MakePointerType(); } else { throw new InvalidOperationException(); } } else if (type.IsGenericParameter) { if (type.DeclaringMethod != null) { throw new NotImplementedException(); } else { return Import(type.DeclaringType).GetGenericArguments()[type.GenericParameterPosition]; } } else if (type.IsGenericType && !type.IsGenericTypeDefinition) { System.Type[] args = type.GetGenericArguments(); Type[] importedArgs = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { importedArgs[i] = Import(args[i]); } return Import(type.GetGenericTypeDefinition()).MakeGenericType(importedArgs); } else { return Import(type.Assembly).GetType(type.FullName); } }
internal System.Type ToReferenceContext(System.Type type) { if (this.InReferenceContext(type)) { return type; } if (type.IsArray) { return Microsoft.JScript.Convert.ToType(Microsoft.JScript.TypedArray.ToRankString(type.GetArrayRank()), this.ToReferenceContext(type.GetElementType())); } return this.JScriptReferenceModule.ResolveType(type.MetadataToken, null, null); }
//While there is a similar method in EditorUtils, due to layouting and especialy no prefix name, this has to be redone a bit differently static object EditorField(object o, System.Type t, bool isPersistent, GUILayoutOption[] layoutOptions) { //Check scene object type for UnityObjects. Consider Interfaces as scene object type. Assumpt that user uses interfaces with UnityObjects var isSceneObjectType = (typeof(Component).IsAssignableFrom(t) || t == typeof(GameObject) || t.IsInterface); if (typeof(UnityEngine.Object).IsAssignableFrom(t) || t.IsInterface){ return UnityEditor.EditorGUILayout.ObjectField((UnityEngine.Object)o, t, isSceneObjectType, layoutOptions); } //Check Type second if (t == typeof(System.Type)){ return EditorUtils.Popup<System.Type>(null, (System.Type)o, UserTypePrefs.GetPreferedTypesList(typeof(object), false), true, layoutOptions ); } t = o != null? o.GetType() : t; if (t.IsAbstract){ GUILayout.Label( string.Format("({0})", t.FriendlyName()), layoutOptions ); return o; } if (o == null && !t.IsAbstract && !t.IsInterface && (t.GetConstructor(System.Type.EmptyTypes) != null || t.IsArray ) ){ if (GUILayout.Button("(null) Create", layoutOptions)){ if (t.IsArray) return System.Array.CreateInstance(t.GetElementType(), 0); return System.Activator.CreateInstance(t); } return o; } if (t == typeof(bool)) return UnityEditor.EditorGUILayout.Toggle((bool)o, layoutOptions); if (t == typeof(Color)) return UnityEditor.EditorGUILayout.ColorField((Color)o, layoutOptions); if (t == typeof(AnimationCurve)) return UnityEditor.EditorGUILayout.CurveField((AnimationCurve)o, layoutOptions); if (t.IsSubclassOf(typeof(System.Enum) )) return UnityEditor.EditorGUILayout.EnumPopup((System.Enum)o, layoutOptions); if (t == typeof(float)){ GUI.backgroundColor = UserTypePrefs.GetTypeColor(t); return UnityEditor.EditorGUILayout.FloatField((float)o, layoutOptions); } if (t == typeof(int)){ GUI.backgroundColor = UserTypePrefs.GetTypeColor(t); return UnityEditor.EditorGUILayout.IntField((int)o, layoutOptions); } if (t == typeof(string)){ GUI.backgroundColor = UserTypePrefs.GetTypeColor(t); return UnityEditor.EditorGUILayout.TextField((string)o, layoutOptions); } if (t == typeof(Vector2)) return UnityEditor.EditorGUILayout.Vector2Field("", (Vector2)o, layoutOptions); if (t == typeof(Vector3)) return UnityEditor.EditorGUILayout.Vector3Field("", (Vector3)o, layoutOptions); if (t == typeof(Vector4)) return UnityEditor.EditorGUILayout.Vector4Field("", (Vector4)o, layoutOptions); if (t == typeof(Quaternion)){ var q = (Quaternion)o; var v = new Vector4(q.x, q.y, q.z, q.w); v = UnityEditor.EditorGUILayout.Vector4Field("", v, layoutOptions); return new Quaternion(v.x, v.y, v.z, v.w); } //If some other type, show it in the generic object editor window if (GUILayout.Button( string.Format("{0} {1}", t.FriendlyName(), (o is IList)? ((IList)o).Count.ToString() : "" ), layoutOptions)) GenericInspectorWindow.Show(o, t); return o; }
/// <summary> /// Converts a value to the specified type using COM conversion rules. /// </summary> private object ChangeTypeForCOM(object source, System.Type type) { // check for conversions to date time from string. if (typeof(string).IsInstanceOfType(source) && type == typeof(DateTime)) { try { return System.Convert.ToDateTime((string)source); } catch {} } // check for conversions from date time to boolean. if (typeof(DateTime).IsInstanceOfType(source) && type == typeof(bool)) { return !(new DateTime(1899, 12, 30, 0, 0, 0).Equals(source)); } // check for conversions from float to double. if (typeof(float).IsInstanceOfType(source) && type == typeof(double)) { return System.Convert.ToDouble((Single)source); } // check for array conversion. if (source.GetType().IsArray && type.IsArray) { ArrayList array = new ArrayList(); foreach (object element in (Array)source) { try { array.Add(ChangeTypeForCOM(element, type.GetElementType())); } catch { throw new ResultIDException(new ResultID(DISP_E_OVERFLOW)); } } return array.ToArray(type.GetElementType()); } else if (!source.GetType().IsArray && !type.IsArray) { IntPtr pvargDest = Marshal.AllocCoTaskMem(16); IntPtr pvarSrc = Marshal.AllocCoTaskMem(16); VariantInit(pvargDest); VariantInit(pvarSrc); Marshal.GetNativeVariantForObject(source, pvarSrc); try { // get vartype. short vt = (short)GetType(type); // change type. int error = VariantChangeTypeEx( pvargDest, pvarSrc, Thread.CurrentThread.CurrentCulture.LCID, VARIANT_NOVALUEPROP | VARIANT_ALPHABOOL, vt); // check error code. if (error != 0) { throw new ResultIDException(new ResultID(error)); } // unmarshal result. object result = Marshal.GetObjectForNativeVariant(pvargDest); // check for invalid unsigned <=> signed conversions. switch ((VarEnum)vt) { case VarEnum.VT_I1: case VarEnum.VT_I2: case VarEnum.VT_I4: case VarEnum.VT_I8: case VarEnum.VT_UI1: case VarEnum.VT_UI2: case VarEnum.VT_UI4: case VarEnum.VT_UI8: { // ignore issue for conversions from boolean. if (typeof(bool).IsInstanceOfType(source)) { break; } decimal sourceAsDecimal = 0; decimal resultAsDecimal = System.Convert.ToDecimal(result); try { sourceAsDecimal = System.Convert.ToDecimal(source); } catch { sourceAsDecimal = 0; } if ((sourceAsDecimal < 0 && resultAsDecimal > 0) || (sourceAsDecimal > 0 && resultAsDecimal < 0)) { throw new ResultIDException(ResultID.Da.E_RANGE); } break; } case VarEnum.VT_R8: { // fix precision problem introduced with conversion from float to double. if (typeof(float).IsInstanceOfType(source)) { result = System.Convert.ToDouble(source.ToString()); } break; } } return result; } finally { VariantClear(pvargDest); VariantClear(pvarSrc); Marshal.FreeCoTaskMem(pvargDest); Marshal.FreeCoTaskMem(pvarSrc); } } else if (source.GetType().IsArray && type == typeof(string)) { int count = ((Array)source).Length; StringBuilder buffer = new StringBuilder(); buffer.Append("{"); foreach (object element in (Array)source) { buffer.Append((string)ChangeTypeForCOM(element, typeof(string))); count--; if (count > 0) { buffer.Append(" | "); } } buffer.Append("}"); return buffer.ToString(); } // no conversions between scalar and array types allowed. throw new ResultIDException(ResultID.Da.E_BADTYPE); }
/// <summary> /// Converts a value to the specified type using .NET conversion rules. /// </summary> private object ChangeType(object source, System.Type type) { try { // check for array conversion. if (source.GetType().IsArray && type.IsArray) { ArrayList array = new ArrayList(); foreach (object element in (Array)source) { try { array.Add(ChangeType(element, type.GetElementType())); } catch { throw new ResultIDException(ResultID.Da.E_BADTYPE); } } return array.ToArray(type.GetElementType()); } else if (!source.GetType().IsArray && !type.IsArray) { if (type == typeof(SByte)) { return System.Convert.ToSByte(source); } if (type == typeof(Byte)) { return System.Convert.ToByte(source); } if (type == typeof(Int16)) { return System.Convert.ToInt16(source); } if (type == typeof(UInt16)) { return System.Convert.ToUInt16(source); } if (type == typeof(Int32)) { return System.Convert.ToInt32(source); } if (type == typeof(UInt32)) { return System.Convert.ToUInt32(source); } if (type == typeof(Int64)) { return System.Convert.ToInt64(source); } if (type == typeof(UInt64)) { return System.Convert.ToUInt64(source); } if (type == typeof(Int64)) { return System.Convert.ToInt64(source); } if (type == typeof(Decimal)) { return System.Convert.ToDecimal(source); } if (type == typeof(String)) { return System.Convert.ToString(source); } if (type == typeof(Single)) { Single output = System.Convert.ToSingle(source); if (Single.IsInfinity(output) || Single.IsNaN(output)) { throw new ResultIDException(ResultID.Da.E_RANGE); } return output; } if (type == typeof(Double)) { Double output = System.Convert.ToDouble(source); if (Double.IsInfinity(output) || Double.IsNaN(output)) { throw new ResultIDException(ResultID.Da.E_RANGE); } return output; } if (type == typeof(DateTime)) { // check for conversions to date time from string. if (typeof(string).IsInstanceOfType(source)) { string dateTime = ((string)source).Trim(); // check for XML schema date/time format. if (dateTime.IndexOf('-') == 4) { try { return System.Xml.XmlConvert.ToDateTime((string)source, XmlDateTimeSerializationMode.Utc); } catch { // ignore errors - try the localized version next. } } } // use default conversion. return System.Convert.ToDateTime(source); } if (type == typeof(Boolean)) { // check for conversions to boolean from string. if (typeof(string).IsInstanceOfType(source)) { string text = ((string)source).Trim().ToLower(); // check for XML schema defined true values. if (text == "true" || text == "1") { return true; } // check for XML schema defined false values. if (text == "false" || text == "0") { return true; } } // use default conversion. return System.Convert.ToBoolean(source); } } else if (source.GetType().IsArray && type == typeof(string)) { int count = ((Array)source).Length; StringBuilder buffer = new StringBuilder(); buffer.Append("{"); foreach (object element in (Array)source) { buffer.Append((string)ChangeType(element, typeof(string))); count--; if (count > 0) { buffer.Append(" | "); } } buffer.Append("}"); return buffer.ToString(); } // no conversions between scalar and array types allowed. throw new ResultIDException(ResultID.Da.E_BADTYPE); } catch (ResultIDException e) { throw e; } catch (Exception e) { throw new ResultIDException(ResultID.Da.E_BADTYPE, e.Message, e); } }
private static string GetListNameFromType(System.Type type) { if (typeof(Array).IsAssignableFrom(type)) { return type.GetElementType().Name; } if (typeof(IList).IsAssignableFrom(type)) { PropertyInfo typedIndexer = GetTypedIndexer(type); if (typedIndexer != null) { return typedIndexer.PropertyType.Name; } return type.Name; } return type.Name; }
public object MapToIdlSequence(System.Type dotNetType, int bound, AttributeExtCollection allAttributes, AttributeExtCollection elemTypeAttributes) { if (m_useAnonymousSequences) { string refToElemType = (string)m_mapper.MapClsType(dotNetType.GetElementType(), elemTypeAttributes, this); return "sequence<" + refToElemType + ">"; } else { // use a typedef for non-anonymous sequence return IdlNaming.GetFullyQualifiedIdlTypeDefAliasForSequenceType(dotNetType, bound, elemTypeAttributes); } }
internal static string MapTypeName(System.Type type) { bool isArray = type.IsArray; System.Type elementType = type.GetElementType(); if (elementType != null) { type = elementType; } string fullName = type.FullName; if (!isArray) { return fullName; } return (fullName + "[]"); }
/// <summary> /// Determines if the two types are either identical, or are both generic parameters or generic types /// with generic parameters in the same locations (generic parameters match any other generic parameter, /// but NOT concrete types). /// </summary> private static bool IsSimilarType(this System.Type thisType, System.Type type) { // Ignore any 'ref' types if (thisType.IsByRef) thisType = thisType.GetElementType(); if (type.IsByRef) type = type.GetElementType(); // Handle array types if (thisType.IsArray && type.IsArray) return thisType.GetElementType().IsSimilarType(type.GetElementType()); // If the types are identical, or they're both generic parameters or the special 'T' type, treat as a match if (thisType == type || ((thisType.IsGenericParameter || thisType == typeof(T)) && (type.IsGenericParameter || type == typeof(T)))) return true; // Handle any generic arguments if (thisType.IsGenericType && type.IsGenericType) { System.Type[] thisArguments = thisType.GetGenericArguments(); System.Type[] arguments = type.GetGenericArguments(); if (thisArguments.Length == arguments.Length) return !thisArguments.Where((t, i) => !t.IsSimilarType(arguments[i])).Any(); } return false; }
/// <summary> Type-munging for field setting and method invocation. /// Conforms to LC3 specification /// </summary> internal static System.Object CoerceType(System.Type type, System.Object value) { if (value != null && value.GetType () == type) { return value; } switch (GetJSTypeCode (value)) { case JSTYPE_NULL: // raise error if type.isPrimitive() if (type.IsPrimitive) { reportConversionError (value, type); } return null; case JSTYPE_UNDEFINED: if (type == typeof (string) || type == typeof (object)) { return "undefined"; } else { reportConversionError ("undefined", type); } break; case JSTYPE_BOOLEAN: // Under LC3, only JS Booleans can be coerced into a Boolean value if (type == typeof (bool) || type == typeof (bool) || type == typeof (object)) { return value; } else if (type == typeof (string)) { return value.ToString (); } else { reportConversionError (value, type); } break; case JSTYPE_NUMBER: if (type == typeof (string)) { return ScriptConvert.ToString (value); } else if (type == typeof (object)) { return CoerceToNumber (typeof (double), value); } else if ((type.IsPrimitive && type != typeof (bool)) || CliHelper.IsNumberType (type)) { return CoerceToNumber (type, value); } else { reportConversionError (value, type); } break; case JSTYPE_STRING: if (type == typeof (string) || type.IsInstanceOfType (value)) { return value; } else if (type == typeof (char)) { // Special case for converting a single char string to a // character // Placed here because it applies *only* to JS strings, // not other JS objects converted to strings if (((System.String)value).Length == 1) { return ((System.String)value) [0]; } else { return CoerceToNumber (type, value); } } else if ((type.IsPrimitive && type != typeof (bool)) || CliHelper.IsNumberType (type)) { return CoerceToNumber (type, value); } else { reportConversionError (value, type); } break; case JSTYPE_CLI_CLASS: if (value is Wrapper) { value = ((Wrapper)value).Unwrap (); } if (type == typeof (Type) || type == typeof (object)) { return value; } else if (type == typeof (string)) { return value.ToString (); } else { reportConversionError (value, type); } break; case JSTYPE_CLI_OBJECT: case JSTYPE_CLI_ARRAY: if (type.IsPrimitive) { if (type == typeof (bool)) { reportConversionError (value, type); } return CoerceToNumber (type, value); } else { if (value is Wrapper) { value = ((Wrapper)value).Unwrap (); } if (type == typeof (string)) { return value.ToString (); } else { if (type.IsInstanceOfType (value)) { return value; } else { reportConversionError (value, type); } } } break; case JSTYPE_OBJECT: if (type == typeof (string)) { return ScriptConvert.ToString (value); } else if (type.IsPrimitive) { if (type == typeof (bool)) { reportConversionError (value, type); } return CoerceToNumber (type, value); } else if (type.IsInstanceOfType (value)) { return value; } else if (type == typeof (DateTime) && value is BuiltinDate) { double time = ((BuiltinDate)value).JSTimeValue; // TODO: This will replace NaN by 0 return BuiltinDate.FromMilliseconds ((long)time); } else if (type.IsArray && value is BuiltinArray) { // Make a new java array, and coerce the JS array components // to the target (component) type. BuiltinArray array = (BuiltinArray)value; long length = array.getLength (); System.Type arrayType = type.GetElementType (); System.Object Result = System.Array.CreateInstance (arrayType, (int)length); for (int i = 0; i < length; ++i) { try { ((System.Array)Result).SetValue (CoerceType (arrayType, array.Get (i, array)), i); } catch (EcmaScriptException) { reportConversionError (value, type); } } return Result; } else if (value is Wrapper) { value = ((Wrapper)value).Unwrap (); if (type.IsInstanceOfType (value)) return value; reportConversionError (value, type); } else { reportConversionError (value, type); } break; } return value; }
private static OpCode GetStindInstruction(System.Type parameterType) { if (parameterType.IsByRef) { OpCode stindOpCode; if(OpCodesMap.TryGetStindOpCode(parameterType.GetElementType(), out stindOpCode)) { return stindOpCode; } } return OpCodes.Stind_Ref; }
public static ODBType GetFromClass(System.Type clazz) { string className = OdbClassUtil.GetFullName(clazz); if (NeoDatis.Tool.Wrappers.OdbClassUtil.IsEnum(clazz)) { ODBType type = new ODBType(ODBType.Enum.isPrimitive, ODBType.EnumId, ODBType.Enum.GetName(), 0); type.SetName(OdbClassUtil.GetFullName(clazz)); return type; } // First check if it is a 'default type' ODBType tc = null; typesByName.TryGetValue(className, out tc); if (tc != null) { return tc; } // Then check if it is a 'non default type' cacheOfTypesByName.TryGetValue(className,out tc); if (tc != null) { return tc; } if (IsArray(clazz)) { ODBType type = new ODBType(ODBType.Array.isPrimitive, ODBType.ArrayId, ODBType.Array.GetName(), 0); type.subType = GetFromClass(clazz.GetElementType()); cacheOfTypesByName.Add(className, type); return type; } if (IsMap(clazz)) { cacheOfTypesByName.Add(className, Map); return Map; } // check if it is a list if (IsCollection(clazz)) { cacheOfTypesByName.Add(className, Collection); return Collection; } nb++; ODBType nonNative = new ODBType(ODBType.NonNative.isPrimitive, NonNativeId , OdbClassUtil.GetFullName(clazz), 0); cacheOfTypesByName.Add(className, nonNative); return nonNative; }
private string GetSimpleTypeFullName(System.Type type) { if (type == null) { return string.Empty; } StringBuilder builder = new StringBuilder(type.FullName); Stack<System.Type> stack = new Stack<System.Type>(); stack.Push(type); while (stack.Count > 0) { type = stack.Pop(); while (type.IsArray) { type = type.GetElementType(); } if (type.IsGenericType && !type.IsGenericTypeDefinition) { foreach (System.Type type2 in type.GetGenericArguments()) { builder.Replace("[" + type2.AssemblyQualifiedName + "]", this.GetSimpleTypeFullName(type2)); stack.Push(type2); } } } return builder.ToString(); }
private string ClazzToName(System.Type cl) { string s = null; if (cl.IsArray) { s = ClazzToName(cl.GetElementType()) + "[]"; } else { s = cl.FullName; } return s; }