GetIndexParameters() 개인적인 메소드

private GetIndexParameters ( ) : System.Reflection.ParameterInfo[]
리턴 System.Reflection.ParameterInfo[]
예제 #1
0
파일: MemberID.cs 프로젝트: tgassner/NDoc
		/// <summary>
		/// 
		/// </summary>
		/// <param name="property"></param>
		/// <returns></returns>
		public static string GetMemberID(PropertyInfo property)
		{
			string memberName;

			memberName = "P:" + GetFullNamespaceName(property) +
				"." + property.Name.Replace('.', '#').Replace('+', '#');

			try
			{
				if (property.GetIndexParameters().Length > 0)
				{
					memberName += "(";

					int i = 0;

					foreach (ParameterInfo parameter in property.GetIndexParameters())
					{
						if (i > 0)
						{
							memberName += ",";
						}

						Type type = parameter.ParameterType;

#if NET_2_0
                        if (type.ContainsGenericParameters && type.IsGenericParameter)
                        {
                            memberName += "`" + type.GenericParameterPosition.ToString();
                        }
                        else if (type.FullName != null)
                        {
                            memberName += type.FullName;
                        }
                        else
                        {
                            memberName += type.Name;
                        }
#else
						memberName += type.FullName;
#endif

						++i;
					}

					memberName += ")";
				}
			}
			catch (System.Security.SecurityException) { }

			return memberName;
		}
예제 #2
0
        internal static InformationApi.PropertyInfo BuildPropInfo(System.Reflection.PropertyInfo f)
        {
            var fi = new InformationApi.PropertyInfo();

            fi.Name        = f.Name;
            fi.Description = GetDescription(f);
            fi.Type        = f.PropertyType.Name;
            fi.CanGet      = f.CanRead;
            fi.CanSet      = f.CanWrite;

            foreach (var pi in f.GetIndexParameters())
            {
                fi.Indizes.Add(BuildArgInfo(pi));
            }

            if (!f.PropertyType.IsSimpleType())
            {
                StructCollector.CollectType(f.PropertyType);
            }

            fi.ThrowsExceptionInfo = BuildExceptionInfo(f);
            //ToDo: continue Funcinfo build!

            return(fi);
        }
예제 #3
0
        public void PrintProperty(SysRef.PropertyInfo property)
        {
            if ((_flags & SignaturePrintingFlags.IgnoreMemberOwner) != SignaturePrintingFlags.IgnoreMemberOwner)
            {
                PrintType(property.DeclaringType);
                _builder.Append("::");
            }

            PrintIdentifier(property.Name);

            // Properties
            {
                var parameters = property.GetIndexParameters();

                _builder.Append("(");

                for (int i = 0; i < parameters.Length; i++)
                {
                    if (i > 0)
                    {
                        _builder.Append(", ");
                    }

                    PrintType(parameters[i].ParameterType, false);
                }

                _builder.Append(")");
            }

            _builder.Append(" : ");
            PrintType(property.PropertyType, false);
        }
예제 #4
0
 private static bool IsAValidProperty(PropertyInfo propertyInfo)
 {
     if (!propertyInfo.CanRead) return false;
     if (!propertyInfo.CanWrite) return false;
     if (propertyInfo.GetIndexParameters().Length > 0) return false;
     return true;
 }
예제 #5
0
		/// <summary>
		/// Check if the property is not null and can be read and is no indexed.
		/// This is done to know if it can be read safely.
		/// </summary>
		/// <param name="obj">Obj.</param>
		/// <param name="prop">Prop.</param>
		/// <returns></returns>
		private static bool PropertyHasValue(object obj, PropertyInfo prop)
		{
			if (obj == null || prop == null || !prop.CanRead || prop.GetIndexParameters().Length > 0)
				return false;
			else
				return true;
		}
        internal static MethodInfo GetPropertySetter(PropertyInfo propertyInfo, Type type)
        {
            if (propertyInfo.DeclaringType == type) return propertyInfo.GetSetMethod(true);
#if NETSTANDARD1_3
            return propertyInfo.DeclaringType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                    .Single(x => x.Name == propertyInfo.Name
                        && x.PropertyType == propertyInfo.PropertyType
                        && IsParameterMatch(x.GetIndexParameters(), propertyInfo.GetIndexParameters())
                        ).GetSetMethod(true);
#else
            return propertyInfo.DeclaringType.GetProperty(
                   propertyInfo.Name,
                   BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                   Type.DefaultBinder,
                   propertyInfo.PropertyType,
                   propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(),
                   null).GetSetMethod(true);
#endif
        }
예제 #7
0
        private static bool HasGetter(PropertyInfo prop)
        {
            if (!prop.CanRead)
                return false;

            if (!ArrayUtil.IsNullOrEmpty(prop.GetIndexParameters()))
                return false;

            return true;
        }
 public bool CanRead(ReflectedInstance value, Type type, PropertyInfo property)
 {
     // verify if property is "this[int i]", in real use is: "myList[0]', exclude array objects
     // because if array is multidimensional will happen a error when call
     // "property.GetValue(obj, new object[] { 0, 0 });" the class "PropertyReaderIndexerInArray" fix it.
     var parameters = property.GetIndexParameters();
     //
     return (parameters.Length == 1)
         && (parameters[0].ParameterType == typeof(int));
 }
        public static string GetId(PropertyInfo property)
        {
            var parameters = string.Join(",", property.GetIndexParameters().Select(x => GetTypeName(x.ParameterType)));

            if (!string.IsNullOrEmpty(parameters))
            {
                parameters = "(" + parameters + ")";
            }

            return string.Format(CultureInfo.InvariantCulture, "P:{0}.{1}{2}", GetTypeName(property.ReflectedType), HashEncode(property.Name), parameters);
        }
예제 #10
0
        public static string GetAssetId(PropertyInfo propertyInfo)
        {
            ParameterInfo[] p = propertyInfo.GetIndexParameters();
            if (p.Length == 0)
                return string.Format("P:{0}.{1}", GetTypeName(propertyInfo.ReflectedType), propertyInfo.Name);

            return string.Format("P:{0}.{1}{2}",
                                 GetTypeName(propertyInfo.ReflectedType),
                                 propertyInfo.Name,
                                 CreateParameterSignature(propertyInfo, p.Select(pr => pr.ParameterType).ToArray()));
        }
예제 #11
0
 internal static string ToSignature (PropertyInfo pi)
 {
     StringBuilder sb = new StringBuilder ();
     sb.Append (ToSignature (pi.PropertyType));
     sb.Append (" ");
     sb.Append (ToSignature (pi.DeclaringType));
     sb.Append (".");
     sb.Append (pi.Name);
     sb.Append (ToSignature ('[', pi.GetIndexParameters (), ']'));
     return sb.ToString ();
 }
예제 #12
0
        private bool IsCandidateProperty(PropertyInfo property)
        {
            if (property == null)
            {
                throw new ArgumentNullException(nameof(property));
            }

            return property.CanWrite &&
                property.GetIndexParameters().Length == 0 &&
                IsSupportedPropertyType(property.PropertyType);
        }
        public IEnumerable<MethodValue> GetValues(ReflectedInstance value, Type type, PropertyInfo property)
        {
            var dictionary = value.Object as IDictionary;
            var parameters = property.GetIndexParameters();

            foreach (var key in dictionary.Keys)
            {
                var parameter = new MethodValueParam(parameters[0].Name, parameters[0], key);
                yield return new MethodValue(dictionary[key], parameter);
            }
        }
예제 #14
0
        private static DependencyObject FindParent(Queue <string> queue, DependencyObject current)
        {
            string propertyName = queue.Dequeue();

            object[] indexParameters = new object[0];
            if (propertyName.Contains('['))
            {
                int start = propertyName.IndexOf('[');
                int end   = propertyName.IndexOf(']');
                if (end != propertyName.Length - 1)
                {
                    throw new InvalidOperationException(Resources.IndexedExpressionsMustBeClosed);
                }

                int length = (end - start) - 1;
                indexParameters = propertyName.Substring(start + 1, length).Split(',').Cast <object>().ToArray();

                propertyName = propertyName.Substring(0, start);
            }

            System.Reflection.PropertyInfo property = current.GetType().GetProperty(propertyName);
            if (property == null)
            {
                throw new InvalidOperationException(string.Format(
                                                        Resources.PropertyNameDoesNotExist,
                                                        propertyName));
            }

            ParameterInfo[] parameters = property.GetIndexParameters();
            if (parameters.Length != indexParameters.Length)
            {
                throw new InvalidOperationException(string.Format(
                                                        Resources.PropertyRequiresIndexArguments,
                                                        parameters.Length,
                                                        indexParameters.Length));
            }

            for (int x = 0; x < parameters.Length; x++)
            {
                indexParameters[x] = Convert.ChangeType(
                    indexParameters[x],
                    parameters[x].ParameterType,
                    CultureInfo.InvariantCulture);
            }

            DependencyObject parent = (DependencyObject)property.GetValue(current, (indexParameters.Length > 0 ? indexParameters : null));

            if (queue.Count > 0)
            {
                parent = FindParent(queue, parent);
            }

            return(parent);
        }
예제 #15
0
        public override bool UseWhen()
        {
            _info = PropertyInfoHelper.GetIndexerPropertyInfo(TargetType, ColumnName);

            if (_info == null)
                return false;

            var parameterType = _info.GetIndexParameters().First().ParameterType;
            _lookUp = Convert.ChangeType(ColumnName, parameterType);

            return true;
        }
예제 #16
0
        private static Type[] GetIndexerTypes(PropertyInfo property)
        {
            var indexerParameters = property.GetIndexParameters();

            var result = new Type[indexerParameters.Length];

            for (var i = 0; i < indexerParameters.Length; i++)
            {
                result[i] = indexerParameters[i].ParameterType;
            }

            return result;
        }
 public override Boolean Match(PropertyInfo sourceProperty, PropertyInfo targetProperty)
 {
     if (sourceProperty.Name == "Item")
     {
         var pp = sourceProperty.GetIndexParameters();
         //source["key1"]
         if (pp.Length == 1 && pp[0].ParameterType == typeof(String))
         {
             return true;
         }
     }
     return false;
 }
예제 #18
0
        public static System.Func <TSource, TRet> CreateGetter <TSource, TRet>(System.Reflection.PropertyInfo propertyInfo, bool nonPublic)
        {
            if (propertyInfo == null)
            {
                throw new System.ArgumentNullException(nameof(propertyInfo));
            }

            if (propertyInfo.GetIndexParameters().Length > 0)
            {
                //throw new System.ArgumentException("Cannot create a dynamic getter for anindexed property.", "propertyInfo");
                return(null);
            }

            if (typeof(TSource) != typeof(object) &&
                !propertyInfo.DeclaringType.IsAssignableFrom(typeof(TSource)))
            {
                //throw new System.ArgumentException("The declaring type of the property is not assignable from the type of the instance.", "propertyInfo");
                return(null);
            }

            if (!typeof(TRet).IsAssignableFrom(propertyInfo.PropertyType))
            {
                //throw new System.ArgumentException("The type of the return value is not assignable from the type of the property.", "propertyInfo");
                return(null);
            }

            //the method call of the get accessor method fails in runtime
            //if the declaring type of the property is an interface and TSource is a value type,
            //in this case, we should find the property from TSource whose DeclaringType is TSource itself

            if (typeof(TSource).GetTypeInfo().IsValueType&& propertyInfo.DeclaringType.GetTypeInfo().IsInterface)
            {
                propertyInfo = typeof(TSource).GetProperty(propertyInfo.Name);
            }

            var getMethod = propertyInfo.GetGetMethod(nonPublic);

            if (getMethod == null)
            {
                //if (nonPublic)
                //{
                //    throw new System.ArgumentException("The property does not have a get method.", "propertyInfo");
                //}

                //throw new System.ArgumentException("The property does not have a public get method.", "propertyInfo");

                return(null);
            }

            return(EmitPropertyGetter <TSource, TRet>(propertyInfo, getMethod));
        }
 public static ExpressionTypeMemberDescriptor Build(PropertyInfo p)
 {
     ExpressionTypeMemberDescriptor md = new ExpressionTypeMemberDescriptor
     {
         Kind = "property",
         Name = p.Name,
         ReturnType = p.PropertyType.Name,
         ReturnExpressionType = p.PropertyType.AssemblyQualifiedName
     };
     md.Parameters = (
         from mdp in p.GetIndexParameters()
         select Build(mdp)).ToList();
     return md;
 }
        static StackObject *GetIndexParameters_10(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.PropertyInfo instance_of_this_method = (System.Reflection.PropertyInfo) typeof(System.Reflection.PropertyInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetIndexParameters();

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
예제 #21
0
        public static System.Action <TTarget, TValue> CreateSetter <TTarget, TValue>(System.Reflection.PropertyInfo propertyInfo, bool nonPublic)
        {
            if (propertyInfo == null)
            {
                throw new System.ArgumentNullException(nameof(propertyInfo));
            }

            if (typeof(TTarget).GetTypeInfo().IsValueType)
            {
                //throw new System.ArgumentException("The type of the isntance should not be a value type. " + "For a value type, use System.Object instead.", "propertyInfo");
                return(null);
            }

            if (propertyInfo.GetIndexParameters().Length > 0)
            {
                //throw new System.ArgumentException("Cannot create a dynamic setter for an indexed property.", "propertyInfo");
                return(null);
            }

            if (typeof(TTarget) != typeof(object) &&
                !propertyInfo.DeclaringType.IsAssignableFrom(typeof(TTarget)))
            {
                //throw new System.ArgumentException("The declaring type of the property is not assignable from the type of the isntance.", "propertyInfo");
                return(null);
            }

            if (typeof(TValue) != typeof(object) &&
                !propertyInfo.PropertyType.IsAssignableFrom(typeof(TValue)))
            {
                //throw new System.ArgumentException("The type of the property is not assignable from the type of the value.", "propertyInfo");
                return(null);
            }

            var setMethod = propertyInfo.GetSetMethod(nonPublic);

            if (setMethod == null)
            {
                //if (nonPublic)
                //{
                //    throw new System.ArgumentException("The property does not have a set method.", "propertyInfo");
                //}

                //throw new System.ArgumentException("The property does not have a public set method.", "propertyInfo");
                return(null);
            }

            return(EmitPropertySetter <TTarget, TValue>(propertyInfo, setMethod));
        }
        static bool CompareProperty(PropertyInfo expectedPropertyInfo, PropertyInfo actualPropertyInfo, object expected, object actual,
                             IComparisonContext comparisonContext, bool areEqual)
        {
            ParameterInfo[] indexes = expectedPropertyInfo.GetIndexParameters();

            if (indexes.Length == 0)
            {
                areEqual = CompareStandardProperty(expectedPropertyInfo, actualPropertyInfo, expected, actual, comparisonContext) &&
                           areEqual;
            }
            else
            {
                areEqual = CompareIndexedProperty(expectedPropertyInfo, expected, actual, indexes, comparisonContext) && areEqual;
            }

            return areEqual;
        }
예제 #23
0
 internal CLSProperty(String name, Type type, MemberInfo[] properties,Boolean isStatic)
 {
     this.isStatic = isStatic;
     this.type = type;
     this.pi = (PropertyInfo)properties[0];
     this.name = name;
     for(int i=0;i<properties.Length;i++)
     {
     PropertyInfo pi = (PropertyInfo)properties[i];
     ParameterInfo[] info = pi.GetIndexParameters();
     if(info.Length > 0) //it's an indexed property - we don't support field-style access
         {
         throw new Exception("Field-style access for indexed property  of: " + type.Name +
                                   " not supported -" +
                                   " use get_" + name + " and set_" + name + " functions instead");
         }
     }
 }
        public IEnumerable<MethodValue> GetValues(ReflectedInstance value, Type type, PropertyInfo property)
        {
            //var converted = obj as System.Collections.ICollection;
            //var len = converted.Count;

            var parameters = property.GetIndexParameters();
            var len = 0;
            if (!ReflectionUtils.TryGetPropertyValue<int>(value.Object, "Count", out len))
                if (!ReflectionUtils.TryGetPropertyValue<int>(value.Object, "Length", out len))
                    throw new Exception("It could not find the size of the indexed property '" + property.Name + "' to iterate.");

            for (int i = 0; i < len; i++)
            {
                var propValue = property.GetValue(value.Object, new object[] { i });
                var parameter = new MethodValueParam(parameters[0].Name, parameters[0], i);
                yield return new MethodValue(propValue, parameter);
            }
        }
예제 #25
0
        public static PropertyInfo LocateMatchingProperty(PropertyInfo property, Type inType)
        {
            var indexParameters = property.GetIndexParameters();
            var indexParameterTypes = new Type[indexParameters.Length];

            for (var i = 0; i < indexParameters.Length; i++)
            {
                indexParameterTypes[i] = indexParameters[i].ParameterType;
            }

            return inType.GetProperty(
                property.Name,
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                property.PropertyType,
                indexParameterTypes,
                null);
        }
예제 #26
0
        private static void WriteObject(System.Text.StringBuilder sb, object o)
        {
            System.Reflection.MemberInfo[] members = o.GetType().GetMembers(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            sb.Append("{");
            bool flag = false;

            System.Reflection.MemberInfo[] array = members;
            for (int i = 0; i < array.Length; i++)
            {
                System.Reflection.MemberInfo memberInfo = array[i];
                bool   flag2 = false;
                object val   = null;
                if ((memberInfo.MemberType & System.Reflection.MemberTypes.Field) == System.Reflection.MemberTypes.Field)
                {
                    System.Reflection.FieldInfo fieldInfo = (System.Reflection.FieldInfo)memberInfo;
                    val   = fieldInfo.GetValue(o);
                    flag2 = true;
                }
                else if ((memberInfo.MemberType & System.Reflection.MemberTypes.Property) == System.Reflection.MemberTypes.Property)
                {
                    System.Reflection.PropertyInfo propertyInfo = (System.Reflection.PropertyInfo)memberInfo;
                    if (propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0)
                    {
                        val   = propertyInfo.GetValue(o, null);
                        flag2 = true;
                    }
                }
                if (flag2)
                {
                    sb.Append("\"");
                    sb.Append(memberInfo.Name);
                    sb.Append("\":");
                    JSONConverter.WriteValue(sb, val);
                    sb.Append(",");
                    flag = true;
                }
            }
            if (flag)
            {
                sb.Length--;
            }
            sb.Append("}");
        }
예제 #27
0
        public PropertyMapInfo(PropertyInfo propertyInfo)
        {
            this.Name = propertyInfo.Name;
            this.PropertyInfo = propertyInfo;

            this.PropertyType = propertyInfo.PropertyType;
            this.IsNullableT = propertyInfo.PropertyType.IsInheritanceFrom(typeof(Nullable<>));
            this.IsIndexedProperty = propertyInfo.GetIndexParameters().Length > 0;
            if (this.IsNullableT == true)
            {
                this.ActualType = propertyInfo.PropertyType.GenericTypeArguments[0];
                this.CanBeNull = true;
            }
            else
            {
                this.ActualType = propertyInfo.PropertyType;
                this.CanBeNull = this.ActualType.IsValueType == false;
            }
        }
예제 #28
0
        internal PropertyMetadata(PropertyInfo info)
        {
            PropertyInfo = info;

            #if !DataAnnotations_Missing
            Validators = ImmutableArray.CreateRange(info.GetCustomAttributes(typeof(ValidationAttribute), true).OfType<ValidationAttribute>());
            #endif

            IsIndexed = info.GetIndexParameters().Length > 0;

            m_GetMethod = PropertyInfo.GetMethod;
            m_SetMethod = PropertyInfo.SetMethod;

            PropertyType = info.PropertyType;

            var name = info.ToString();
            Name = name.Substring(name.IndexOf(" ", StringComparison.Ordinal) + 1);

            if (IsIndexed)
                PropertyChangedEventArgs = new PropertyChangedEventArgs(info.Name + "[]");
            else
                PropertyChangedEventArgs = new PropertyChangedEventArgs(info.Name);

            #if !DataAnnotations_Missing
            IsKey = info.GetCustomAttributes(typeof(KeyAttribute), true).Any();

            var doNotMap = info.GetCustomAttributes(typeof(NotMappedAttribute), true).Any();
            if (!doNotMap)
            {
                var column = (ColumnAttribute)info.GetCustomAttributes(typeof(ColumnAttribute), true).SingleOrDefault();
                MappedColumnName = column != null ? column.Name : Name;
            }
            var decomposeAttribute = (DecomposeAttribute)(info.GetCustomAttributes(typeof(DecomposeAttribute), true).FirstOrDefault());
            if (decomposeAttribute != null)
            {
                Decompose = true;
                DecompositionPrefix = decomposeAttribute.Prefix;
            }
            IgnoreOnInsert = info.GetCustomAttributes(typeof(IgnoreOnInsertAttribute), true).Any();
            IgnoreOnUpdate = info.GetCustomAttributes(typeof(IgnoreOnUpdateAttribute), true).Any();
            #endif
        }
예제 #29
0
        private bool UseWhenProperty(string firstColumnName)
        {
            _info = PropertyInfoHelper.GetCaseInsensitivePropertyInfo(
                TargetType, firstColumnName);

            if (_info != null)
                return true;

            _info = PropertyInfoHelper.GetIndexerPropertyInfo(
                TargetType, firstColumnName);

            if (_info == null)
                return false;

            _isIndexer = true;

            var parameterType = _info.GetIndexParameters().First().ParameterType;
            _lookUp = Convert.ChangeType(firstColumnName, parameterType);

            return true;
        }
예제 #30
0
 private string GeneratePropertyCaption(PropertyInfo pi)
 {
     ParameterInfo[] indexParameters = pi.GetIndexParameters();
     if ((indexParameters == null) || (indexParameters.Length == 0))
     {
         return pi.Name;
     }
     StringBuilder builder = new StringBuilder(0x100);
     builder.Append(pi.Name);
     builder.Append('[');
     for (int i = 0; i < indexParameters.Length; i++)
     {
         if (i != 0)
         {
             builder.Append(", ");
         }
         builder.Append(indexParameters[i].ParameterType.Name);
     }
     builder.Append(']');
     return builder.ToString();
 }
예제 #31
0
        public Indexer(Class declaringType, SR.PropertyInfo tinfo)
        {
            this.declaringType = declaringType;

            ModifierEnum mod = (ModifierEnum)0;

            modifiers = mod;

            this.FullyQualifiedName = tinfo.Name;
            returnType      = new ReturnType(tinfo.PropertyType);
            this.region     = Class.GetRegion();
            this.bodyRegion = Class.GetRegion();

            LoadXml(declaringType);

            // Add parameters
            foreach (SR.ParameterInfo pinfo in tinfo.GetIndexParameters())
            {
                parameters.Add(new Parameter(this, pinfo, node));
            }
        }
        public IEnumerable<MethodValue> GetValues(ReflectedInstance value, Type type, PropertyInfo property)
        {
            var converted = value.Object as Son;
            var len = converted.List.Count;
            var parameters = property.GetIndexParameters();

            // this[int index]
            if (parameters.Length == 1 && parameters[0].ParameterType == typeof(int))
            {
                for (int i = 0; i < len; i++)
                {
                    var propValue = property.GetValue(value.Object, new object[] { i });
                    var parameter = new MethodValueParam(parameters[0].Name, parameters[0], i);
                    yield return new MethodValue(propValue, parameter);
                }
            }

            // this[int index, int index2]
            if (parameters.Length == 2 && parameters[0].ParameterType == typeof(int) && parameters[1].ParameterType == typeof(int))
            {
                for (int i = 0; i < len; i++)
                {
                    var propValue = property.GetValue(value.Object, new object[] { i, 0 });
                    var parameter1 = new MethodValueParam(parameters[0].Name, parameters[0], i);
                    var parameter2 = new MethodValueParam(parameters[1].Name, parameters[1], 0);
                    yield return new MethodValue(propValue, parameter1, parameter2);
                }
            }

            // this[string contains]
            if (parameters.Length == 1 && parameters[0].ParameterType == typeof(string))
            {
                for (int i = 0; i < len; i++)
                {
                    var propValue = property.GetValue(value.Object, new object[] { "list " + i });
                    var parameter1 = new MethodValueParam(parameters[0].Name, parameters[0], "list " + i);
                    yield return new MethodValue(propValue, parameter1);
                }
            }
        }
        public static bool IsDerivedFrom(this PropertyInfo a_pi, PropertyInfo a_base,
            bool a_with_this = false)
        {
            if (a_pi.Name != a_base.Name)
                return false;
            if (a_pi.PropertyType != a_base.PropertyType)
                return false;
            if (!a_pi.GetIndexParameters().Select(p => p.ParameterType).SequenceEqual(
                a_base.GetIndexParameters().Select(p => p.ParameterType)))
            {
                return false;
            }
            if (a_pi.DeclaringType == a_base.DeclaringType)
                return a_with_this;

            MethodInfo m1 = a_pi.GetGetMethod(true);
            MethodInfo m3 = a_base.GetGetMethod(true);

            if ((m1 != null) && (m3 != null))
            {
                if (m1.GetBaseDefinitions().ContainsAny(m3.GetBaseDefinitions(true)))
                    return true;
            }
            else if ((m1 != null) || (m3 != null))
                return false;

            MethodInfo m2 = a_pi.GetSetMethod(true);
            MethodInfo m4 = a_base.GetSetMethod(true);

            if ((m2 != null) && (m4 != null))
            {
                if (m2.GetBaseDefinitions().ContainsAny(m4.GetBaseDefinitions(true)))
                    return true;
            }
            else if ((m2 != null) || (m4 != null))
                return false;

            return false;
        }
예제 #34
0
            Property LoadProperty(System.Reflection.PropertyInfo refProperty)
            {
                bool isStatic =
                    (refProperty.CanRead && refProperty.GetGetMethod().IsStatic) ||
                    (refProperty.CanRead && refProperty.GetGetMethod().IsStatic);

                System.Reflection.MethodInfo getMethod =
                    (refProperty.CanRead ? refProperty.GetGetMethod(false) : null);
                System.Reflection.MethodInfo setMethod =
                    (refProperty.CanWrite ? refProperty.GetSetMethod(false) : null);
                Property property = new Property
                {
                    Name         = refProperty.Name,
                    IsStatic     = isStatic,
                    PropertyType = GetTypeFullName(refProperty.PropertyType),
                    GetMethod    = (getMethod != null ? LoadMethod(getMethod) : null),
                    SetMethod    = (setMethod != null ? LoadMethod(setMethod) : null),
                    Attributes   = refProperty.Attributes,
                };

                property.IndexParameters = refProperty.GetIndexParameters().Select(p => LoadParameter(p)).ToList();
                return(property);
            }
예제 #35
0
        /////////////////////////////////////////////////////////////////////////////////

        private PropertySymbol AddPropertyToSymbolTable(PropertyInfo property, AggregateSymbol aggregate)
        {
            Name name;
            bool isIndexer = property.GetIndexParameters() != null && property.GetIndexParameters().Length != 0;

            if (isIndexer)
            {
                name = GetName(SpecialNames.Indexer);
            }
            else
            {
                name = GetName(property.Name);
            }
            PropertySymbol prop = _symbolTable.LookupSym(
                name,
                aggregate,
                symbmask_t.MASK_PropertySymbol) as PropertySymbol;

            // If we already had one, see if it matches.
            if (prop != null)
            {
                PropertySymbol prevProp = null;

                // We'll have multiple properties with the same name if we have indexers.
                // In that case, we need to look at every indexer to see if we find one with
                // the matching associated sym that we want.
                while (prop != null)
                {
                    if (prop.AssociatedPropertyInfo.IsEquivalentTo(property))
                    {
                        return prop;
                    }

                    prevProp = prop;
                    prop = _semanticChecker.SymbolLoader.LookupNextSym(prop, prop.parent, symbmask_t.MASK_PropertySymbol).AsPropertySymbol();
                }

                prop = prevProp;
                if (isIndexer)
                {
                    // We have an indexer for a different property info, so 
                    // create a new symbol for it.
                    prop = null;
                }
            }

            // If we already had a property but its associated info doesn't match,
            // then we repurpose the property that we've found. This can happen
            // in the case of generic instantiations. 
            //
            // Note that this is a bit of a hack - the best way to fix this is 
            // by not depending on the instantiated properties at all, but rather depending
            // on their non-instantiated generic form, which can be gotten from the
            // parent's generic type definition's member. From there, we'll also need to 
            // keep track of the instantiation as we move along, so that when we need the
            // associated property, we can instantiate it correctly.
            //
            // This seems far too heavyweight - since we know we will never bind to more
            // than one property per payload, lets just blast it each time.
            if (prop == null)
            {
                if (isIndexer)
                {
                    prop = _semanticChecker.GetSymbolLoader().GetGlobalMiscSymFactory().CreateIndexer(name, aggregate, GetName(property.Name), null);
                    prop.Params = CreateParameterArray(null, property.GetIndexParameters());
                }
                else
                {
                    prop = _symFactory.CreateProperty(GetName(property.Name), aggregate, null);
                    prop.Params = BSYMMGR.EmptyTypeArray();
                }
            }
            prop.AssociatedPropertyInfo = property;

            prop.isStatic = property.GetGetMethod(true) != null ? property.GetGetMethod(true).IsStatic : property.GetSetMethod(true).IsStatic;
            prop.isParamArray = DoesMethodHaveParameterArray(property.GetIndexParameters());
            prop.swtSlot = null;
            prop.RetType = GetCTypeFromType(property.PropertyType);
            prop.isOperator = isIndexer;

            // Determine if its an override. We should always have an accessor, unless
            // the metadata was bogus.
            if (property.GetMethod != null || property.SetMethod != null)
            {
                MethodInfo accessor = property.GetMethod ?? property.SetMethod; // Must have at least one.
                prop.isOverride = accessor.IsVirtual && accessor.IsHideBySig && accessor.GetRuntimeBaseDefinition() != accessor;
                prop.isHideByName = !accessor.IsHideBySig;
            }

            SetParameterDataForMethProp(prop, property.GetIndexParameters());

            // Get and set.
            MethodInfo methGet = property.GetMethod;
            MethodInfo methSet = property.SetMethod;
            ACCESS access = ACCESS.ACC_PRIVATE;
            if (methGet != null)
            {
                prop.methGet = AddMethodToSymbolTable(methGet, aggregate, MethodKindEnum.PropAccessor);

                // If we have an indexed property, leave the method as a method we can call,
                // and mark the property as bogus.
                if (isIndexer || prop.methGet.Params.size == 0)
                {
                    prop.methGet.SetProperty(prop);
                }
                else
                {
                    prop.setBogus(true);
                    prop.methGet.SetMethKind(MethodKindEnum.Actual);
                }

                if (prop.methGet.GetAccess() > access)
                {
                    access = prop.methGet.GetAccess();
                }
            }
            if (methSet != null)
            {
                prop.methSet = AddMethodToSymbolTable(methSet, aggregate, MethodKindEnum.PropAccessor);

                // If we have an indexed property, leave the method as a method we can call,
                // and mark the property as bogus.
                if (isIndexer || prop.methSet.Params.size == 1)
                {
                    prop.methSet.SetProperty(prop);
                }
                else
                {
                    prop.setBogus(true);
                    prop.methSet.SetMethKind(MethodKindEnum.Actual);
                }

                if (prop.methSet.GetAccess() > access)
                {
                    access = prop.methSet.GetAccess();
                }
            }

            // The access of the property is the least restrictive access of its getter/setter.
            prop.SetAccess(access);

            return prop;
        }
예제 #36
0
        private ProtoCore.AST.AssociativeAST.AssociativeNode ParseProperty(PropertyInfo p)
        {
            if (null == p || SupressesImport(p))
                return null;
            
            //Index properties are not parsed as property at this moment.
            ParameterInfo[] indexParams = p.GetIndexParameters();
            if (null != indexParams && indexParams.Length > 0)
                return null;

            MethodInfo m = p.GetAccessors(false)[0];
            //If this method hides the base class accessor method by signature
            if (m.IsHideBySig)
            {
                //Check if it has a base class
                Type baseType = p.DeclaringType.BaseType;
                PropertyInfo baseProp = (baseType != null) ? GetProperty(ref baseType, p.Name) : null;
                //If this property is also declared in base class, then no need to add this is derived class.
                if(null != baseProp && baseProp.DeclaringType != p.DeclaringType)
                {
                    //base class also has this method.
                    return null;
                }
            }
            
            ProtoCore.AST.AssociativeAST.VarDeclNode varDeclNode = ParseArgumentDeclaration(p.Name, p.PropertyType);
            if(null != varDeclNode)
                varDeclNode.IsStatic = m.IsStatic;
            return varDeclNode;
        }
예제 #37
0
	void OutlineProperty (PropertyInfo pi)
	{
		ParameterInfo [] idxp = pi.GetIndexParameters ();
		MethodBase g = pi.GetGetMethod (true);
		MethodBase s = pi.GetSetMethod (true);
		MethodBase accessor = g != null ? g : s;
		
		if (pi.CanRead && pi.CanWrite) {

			
			// Get the more accessible accessor
			if ((g.Attributes & MethodAttributes.MemberAccessMask) !=
			    (s.Attributes & MethodAttributes.MemberAccessMask)) {
				
				if (g.IsPublic) accessor = g;
				else if (s.IsPublic) accessor = s;
				else if (g.IsFamilyOrAssembly) accessor = g;
				else if (s.IsFamilyOrAssembly) accessor = s;
				else if (g.IsAssembly || g.IsFamily) accessor = g;
				else if (s.IsAssembly || s.IsFamily) accessor = s;
			}
		}
		
		o.Write (GetMethodVisibility (accessor));
		o.Write (GetMethodModifiers  (accessor));
		o.Write (FormatType (pi.PropertyType));
		o.Write (" ");
		
		if (idxp.Length == 0)
			o.Write (pi.Name);
		else {
			o.Write ("this [");
			OutlineParams (idxp);
			o.Write ("]");
		}
		
		o.WriteLine (" {");
		o.Indent ++;
		
		if (g != null && ShowMember (g)) {
			if ((g.Attributes & MethodAttributes.MemberAccessMask) !=
			    (accessor.Attributes & MethodAttributes.MemberAccessMask))
				o.Write (GetMethodVisibility (g));
			o.WriteLine ("get;");
		}
		
		if (s != null && ShowMember (s)) {
			if ((s.Attributes & MethodAttributes.MemberAccessMask) !=
			    (accessor.Attributes & MethodAttributes.MemberAccessMask))
				o.Write (GetMethodVisibility (s));
			o.WriteLine ("set;");
		}
		
		o.Indent --;
		o.Write ("}");
	}
 public static bool IsIndexer(this System.Reflection.PropertyInfo propertyInfo)
 {
     return(propertyInfo.GetIndexParameters().Length > 0);
 }
예제 #39
0
        //Deep copy with reflection
        public static object Copy(this object obj)
        {
            Object targetDeepCopyObj;
            Type   targetType = obj.GetType();

            //if value type, return directly
            if (targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }
            //ref type
            else
            {
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //new instance
                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, Copy(fieldValue));
                        }
                    }
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            object propertyValue;
                            int    noOfParameters = myProperty.GetIndexParameters().Count();
                            //if (noOfParameters == 0)
                            //{
                            //Non-Indexed PROPERTY
                            propertyValue = myProperty.GetValue(obj, null);
                            //}
                            //else
                            //{
                            //Indexed PROPERTY

                            //object[] indexArgs = new object[((IList)myProperty).Count];
                            //for (int i = 0; i < ((IList)myProperty).Count; i++)
                            //{
                            //    indexArgs[i] = i;
                            //}
                            //    propertyValue = myProperty.GetValue(obj, new object[] { 0});
                            //}

                            if (propertyValue is ICloneable)
                            {
                                myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);
                            }
                        }
                    }
                }
            }
            return(targetDeepCopyObj);
        }
예제 #40
0
        static private void AppendPropertyInfo(PropertyInfo property, StringBuilder sb)
        {
            sb.Append(".property ");

            foreach (var attribute in property.GetCustomAttributesData())
            {
                AppendCustomAttributeData(attribute, sb);
                sb.Append(" ");
            }
            foreach (var modreq in property.GetRequiredCustomModifiers())
            {
                sb.Append("modreq(");
                AppendType(modreq, sb);
                sb.Append(") ");
            }
            foreach (var modopt in property.GetOptionalCustomModifiers())
            {
                sb.Append("modopt(");
                AppendType(modopt, sb);
                sb.Append(") ");
            }

            if (property.CanRead && property.CanWrite)
            {
                sb.Append("readwrite ");
            }
            else if (property.CanRead)
            {
                sb.Append("readonly ");
            }
            else if (property.CanWrite)
            {
                sb.Append("writeonly ");
            }

            if (property.Attributes.HasFlag(PropertyAttributes.SpecialName)) sb.Append("specialname ");
            if (property.Attributes.HasFlag(PropertyAttributes.RTSpecialName)) sb.Append("rtspecialname ");

            var propertyAccesors = property.GetAccessors();
            if (propertyAccesors.Length > 0)
            {
                sb.Append(propertyAccesors[0].IsStatic ? "static " : "instance ");
            }
            AppendType(property.PropertyType, sb);
            sb.Append(" ");
            sb.Append(property.Name);

            var indexParameters = property.GetIndexParameters();
            if (indexParameters.Length > 0)
            {
                sb.Append("(");
                foreach (var indexParameter in indexParameters)
                {
                    AppendParameterInfo(indexParameter, sb);
                    AppendComma(sb);
                }
                RemoveTrailingComma(sb);
                sb.Append(")");
            }
        }
예제 #41
0
        private bool IsValidIndexer(PropertyInfo info, string breadCrumb)
        {
            ParameterInfo[] indexers = info.GetIndexParameters();

            if (indexers.Length == 0)
            {
                return false;
            }

            if (indexers.Length > 1)
            {
                throw new Exception("Cannot compare objects with more than one indexer for object " + breadCrumb);
            }

            if (indexers[0].ParameterType != typeof(Int32))
            {
                throw new Exception("Cannot compare objects with a non integer indexer for object " + breadCrumb);
            }

            if (info.ReflectedType.GetProperty("Count") == null)
            {
                throw new Exception("Indexer must have a corresponding Count property for object " + breadCrumb);
            }

            if (info.ReflectedType.GetProperty("Count").PropertyType != typeof(Int32))
            {
                throw new Exception("Indexer must have a corresponding Count property that is an integer for object " + breadCrumb);
            }

            return true;
        }
예제 #42
0
            public override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
            {
                if (match == null || match.Length == 0)
                {
                    throw new ArgumentException("No properties provided", "match");
                }
                bool         flag         = returnType != null;
                int          num          = (indexes == null) ? -1 : indexes.Length;
                PropertyInfo propertyInfo = null;
                int          num2         = 2147483646;
                int          num3         = int.MaxValue;
                int          num4         = 0;

                for (int i = match.Length - 1; i >= 0; i--)
                {
                    PropertyInfo    propertyInfo2   = match[i];
                    ParameterInfo[] indexParameters = propertyInfo2.GetIndexParameters();
                    if (num < 0 || num == indexParameters.Length)
                    {
                        if (!flag || propertyInfo2.PropertyType == returnType)
                        {
                            int num5 = 2147483646;
                            if (num > 0)
                            {
                                num5 = Binder.Default.check_arguments_with_score(indexes, indexParameters);
                                if (num5 == -1)
                                {
                                    goto IL_10E;
                                }
                            }
                            int derivedLevel = Binder.GetDerivedLevel(propertyInfo2.DeclaringType);
                            if (propertyInfo != null)
                            {
                                if (num2 < num5)
                                {
                                    goto IL_10E;
                                }
                                if (num2 == num5)
                                {
                                    if (num4 == derivedLevel)
                                    {
                                        num3 = num5;
                                        goto IL_10E;
                                    }
                                    if (num4 > derivedLevel)
                                    {
                                        goto IL_10E;
                                    }
                                }
                            }
                            propertyInfo = propertyInfo2;
                            num2         = num5;
                            num4         = derivedLevel;
                        }
                    }
                    IL_10E :;
                }
                if (num3 <= num2)
                {
                    throw new AmbiguousMatchException();
                }
                return(propertyInfo);
            }
예제 #43
0
            public override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
            {
                if (match == null || match.Length == 0)
                {
                    throw new ArgumentException("No properties provided", "match");
                }

                bool         haveRet = (returnType != null);
                int          idxlen  = (indexes != null) ? indexes.Length : -1;
                PropertyInfo result  = null;
                int          i;
                int          best_score = Int32.MaxValue - 1;
                int          fail_score = Int32.MaxValue;
                int          level      = 0;

                for (i = match.Length - 1; i >= 0; i--)
                {
                    PropertyInfo    p    = match [i];
                    ParameterInfo[] args = p.GetIndexParameters();
                    if (idxlen >= 0 && idxlen != args.Length)
                    {
                        continue;
                    }

                    if (haveRet && !check_type(p.PropertyType, returnType))
                    {
                        continue;
                    }

                    int score = Int32.MaxValue - 1;
                    if (idxlen > 0)
                    {
                        score = check_arguments_with_score(indexes, args);
                        if (score == -1)
                        {
                            continue;
                        }
                    }

                    int new_level = GetDerivedLevel(p.DeclaringType);
                    if (result != null)
                    {
                        if (best_score < score)
                        {
                            continue;
                        }

                        if (best_score == score)
                        {
                            if (level == new_level)
                            {
                                // Keep searching. May be there's something
                                // better for us.
                                fail_score = score;
                                continue;
                            }

                            if (level > new_level)
                            {
                                continue;
                            }
                        }
                    }

                    result     = p;
                    best_score = score;
                    level      = new_level;
                }

                if (fail_score <= best_score)
                {
                    throw new AmbiguousMatchException();
                }

                return(result);
            }
 public static bool IsCandidateProperty(this PropertyInfo propertyInfo, bool needsWrite = true)
 => !propertyInfo.IsStatic() &&
 (propertyInfo.GetIndexParameters().Length == 0) &&
 propertyInfo.CanRead &&
 (!needsWrite || propertyInfo.CanWrite) &&
 (propertyInfo.GetMethod != null && propertyInfo.GetMethod.IsPublic);
 public static bool IsCandidateProperty(this PropertyInfo propertyInfo, bool needsWrite = true, bool publicOnly = true)
 => !propertyInfo.IsStatic() &&
 propertyInfo.GetIndexParameters().Length == 0 &&
 propertyInfo.CanRead &&
 (!needsWrite || propertyInfo.FindSetterProperty() != null) &&
 propertyInfo.GetMethod != null && (!publicOnly || propertyInfo.GetMethod.IsPublic);
예제 #46
0
        public void toJSON(System.Text.StringBuilder sb, object obj, string format)
        {
            if (obj == null)
            {
                sb.Append("null"); return;
            }

            #region Base

            if (obj == null || obj == System.DBNull.Value)
            {
                sb.Append("null");
                return;
            }
            if (obj is double || obj is float || obj is long || obj is int || obj is short || obj is byte || obj is decimal)
            {
                sb.AppendFormat(System.Globalization.CultureInfo.InvariantCulture.NumberFormat, "{0}", obj);
                return;
            }
            if (obj.GetType().IsEnum)
            {
                sb.Append((int)obj);
                return;
            }
            if (obj is bool)
            {
                sb.Append(obj.ToString().ToLower());
                return;
            }
            if (obj is string || obj is Guid)
            {
                System.Text.StringBuilder sbtemp = new System.Text.StringBuilder();
                if (obj is Guid && obj != null)
                {
                    obj = obj.ToString();
                }
                sbtemp.Append("\"");
                string s = obj as string;
                if (s == null)
                {
                    sbtemp.Append("\"");
                    sb.Append(sbtemp.ToString());
                    return;
                }
                foreach (char c in s)
                {
                    switch (c)
                    {
                    case '\"':
                        sbtemp.Append("\\\"");
                        break;

                    case '\\':
                        sbtemp.Append("\\\\");
                        break;

                    case '\b':
                        sbtemp.Append("\\b");
                        break;

                    case '\f':
                        sbtemp.Append("\\f");
                        break;

                    case '\n':
                        sbtemp.Append("\\n");
                        break;

                    case '\r':
                        sbtemp.Append("\\r");
                        break;

                    case '\t':
                        sbtemp.Append("\\t");
                        break;

                    default:
                        int i = (int)c;
                        if (i < 32 || i > 127)
                        {
                            sbtemp.Append(c);
                            // sbtemp.AppendFormat("\\u{0:X04}", i);
                        }
                        else
                        {
                            sbtemp.Append(c);
                        }
                        break;
                    }
                }
                sbtemp.Append("\"");
                sb.Append(sbtemp.ToString());
                return;
            }
            if (obj is DateTime)
            {
                sb.Append("\"");
                sb.Append(((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss"));
                sb.Append("\"");

                /*
                 * //en-US
                 * SB.Append("new Date(\"");
                 * DateTime TDateTime = (DateTime)Obj;
                 *
                 * TDateTime = TDateTime.ToLocalTime();
                 *
                 * SB.Append(TDateTime.ToString("MMMM, d yyyy HH:mm:ss", new System.Globalization.CultureInfo("en-US", false).DateTimeFormat));
                 * SB.Append("\")");
                 */

                return;
            }



            #endregion Base

            #region JsonBase

            if (obj is JsonNumber)
            {
                sb.AppendFormat(System.Globalization.CultureInfo.InvariantCulture.NumberFormat, "{0}", obj);
                return;
            }
            if (obj is JsonBoolean)
            {
                sb.Append(((JsonBoolean)obj).Value.ToLower());
                return;
            }
            if (obj is JsonString)
            {
                toJSON(sb, obj + "", format);
                return;
            }
            if (obj is JsonDate)
            {
                toJSON(sb, ((JsonDate)obj).getDate(), format);
                return;
            }


            #endregion JsonBase

            #region System.Data
            if (obj is System.Data.DataSet)
            {
                System.Data.DataSet DS = obj as System.Data.DataSet;
                sb.Append("{\"Tables\":{");
                foreach (System.Data.DataTable DT in DS.Tables)
                {
                    sb.AppendFormat("\"{0}\":", DT.TableName);
                    toJSON(sb, DT, format);
                    sb.Append(",");
                }
                // Remove the trailing comma.
                if (DS.Tables.Count > 0)
                {
                    --sb.Length;
                }
                sb.Append("}}");
                return;
            }
            if (obj is System.Data.DataTable)
            {
                sb.Append("{\"Rows\":[");
                System.Data.DataTable DT = obj as System.Data.DataTable;
                foreach (System.Data.DataRow DR in DT.Rows)
                {
                    toJSON(sb, DR, format);
                    sb.Append(",");
                }
                // Remove the trailing comma.
                if (DT.Rows.Count > 0)
                {
                    --sb.Length;
                }
                sb.Append("]}");
                return;
            }
            if (obj is System.Data.DataRow)
            {
                sb.Append("{");
                System.Data.DataRow DR = obj as System.Data.DataRow;
                foreach (System.Data.DataColumn Column in DR.Table.Columns)
                {
                    sb.AppendFormat("\"{0}\":", Column.ColumnName);
                    toJSON(sb, DR[Column], format);
                    sb.Append(",");
                }
                // Remove the trailing comma.
                if (DR.Table.Columns.Count > 0)
                {
                    --sb.Length;
                }
                sb.Append("}");
                return;
            }
            #endregion System.Data

            #region Item Check

            System.Reflection.PropertyInfo PI = obj.GetType().GetProperty("Item");

            #region Object
            if (PI != null && obj.GetType().GetProperty("Keys") != null)
            {
                System.Reflection.PropertyInfo PIK = obj.GetType().GetProperty("Keys");
                object   okeys = PIK.GetValue(obj, null);
                string[] skeys = null;
                if (okeys is string[])
                {
                    skeys = (string[])okeys;
                }

                if (skeys == null)
                {
                    System.Reflection.MethodInfo   MH  = okeys.GetType().GetMethod("CopyTo");
                    System.Reflection.PropertyInfo PIC = okeys.GetType().GetProperty("Count");
                    int count = 0;
                    if (PIC != null)
                    {
                        count = (int)PIC.GetValue(okeys, null);
                    }


                    if (count > 0 && MH != null && MH.GetParameters().Length > 0 && MH.GetParameters()[0].ParameterType == typeof(System.Array))
                    {
                        System.Array akeys = System.Array.CreateInstance(typeof(object), count);
                        MH.Invoke(okeys, new object[] { akeys, 0 });
                        skeys = new string[count];
                        int i = 0;
                        foreach (object key in akeys)
                        {
                            if (!(key is string))
                            {
                                continue;
                            }
                            if (key + "" == "")
                            {
                                continue;
                            }
                            skeys[i] = key + "";
                            i++;
                        }
                    }
                    else if (count > 0 && MH != null && MH.GetParameters().Length > 0 && MH.GetParameters()[0].ParameterType == typeof(string[]))
                    {
                        skeys = new string[count];
                        MH.Invoke(okeys, new object[] { skeys, 0 });
                    }
                }
                //if (skeys != null && skeys.Length > 0){
                sb.Append("{");
                int c = 0;
                for (int i = 0; skeys != null && i < skeys.Length; i++)
                {
                    string key = skeys[i]; if (key == null)
                    {
                        continue;
                    }

                    if (c != 0)
                    {
                        sb.Append(",");
                    }
                    sb.Append("\"" + key + "\":");
                    toJSON(sb, PI.GetValue(obj, new object[] { key }), format);

                    c++;
                }
                sb.Append("}");
                //}

                return;
            }
            #endregion Object

            else if (PI != null && (obj.GetType().GetProperty("Count") != null || obj.GetType().GetProperty("Length") != null) && PI.GetIndexParameters().Length > 0 && PI.GetIndexParameters()[0].ParameterType == typeof(int))
            {
                int c = 0;
                if (c == 0 && obj.GetType().GetProperty("Count").GetValue(obj, null) != null)
                {
                    c = (int)obj.GetType().GetProperty("Count").GetValue(obj, null);
                }
                else if (c == 0 && obj.GetType().GetProperty("Length").GetValue(obj, null) != null)
                {
                    c = (int)obj.GetType().GetProperty("Length").GetValue(obj, null);
                }
                //if (c > 0){
                sb.Append("[");
                for (int i = 0; i < c; i++)
                {
                    if (i != 0)
                    {
                        sb.Append(",");
                    }

                    toJSON(sb, PI.GetValue(obj, new object[] { i }), format);
                }

                sb.Append("]");

                // }

                return;
            }
            #endregion Item Check

            #region Array
            if (obj.GetType().GetProperty("Length") != null && obj.GetType().GetMethod("GetValue", new Type[] { typeof(int) }) != null)
            {
                int l = (int)obj.GetType().GetProperty("Length").GetValue(obj, null);
                //if (l > 0){
                sb.Append("[");
                for (int i = 0; i < l; i++)
                {
                    if (i != 0)
                    {
                        sb.Append(",");
                    }
                    toJSON(sb, obj.GetType().GetMethod("GetValue", new Type[] { typeof(int) }).Invoke(obj, new object[] { i }), format);
                }
                sb.Append("]");
                // }
                return;
            }
            #endregion Array



            #region other
            if (obj is System.Collections.IEnumerable)
            {
                bool hasItems = false;
                System.Collections.IEnumerable e = obj as System.Collections.IEnumerable;

                sb.Append("[");
                foreach (object val in e)
                {
                    toJSON(sb, val, format);
                    sb.Append(",");
                    hasItems = true;
                }
                // Remove the trailing comma.
                if (hasItems)
                {
                    --sb.Length;
                }
                sb.Append("]");
                return;
            }
            #endregion other


            sb.Append("\"" + obj.GetType().FullName + "\"");
        }