GetType() private method

private GetType ( ) : Type
return Type
Exemplo n.º 1
1
 private void field_DataBinding(Object sender, EventArgs e)
 {
     Control c = (Control)sender;
     GridViewRow row = (GridViewRow)c.NamingContainer;
     if (sender.GetType() == typeof(Label))
     {
         (c as Label).Text = DataBinder.Eval(row.DataItem, columnNameData).ToString();
         (c as Label).Font.Size = 7;
         (c as Label).Font.Name = "Arial";
     }
     else if (sender.GetType() == typeof(TextBox))
     {
         (c as TextBox).Text = DataBinder.Eval(row.DataItem, columnNameData).ToString();
         (c as TextBox).Font.Size = 7;
         (c as TextBox).Font.Name = "Arial";
     }
     else if (sender.GetType() == typeof(DropDownList))
     {
         (c as DropDownList).SelectedValue = DataBinder.Eval(row.DataItem, columnNameData).ToString();
         (c as DropDownList).Font.Size = 7;
         (c as DropDownList).Font.Name = "Arial";
     }
     else if (sender.GetType() == typeof(CheckBox))
     {
         (c as CheckBox).Checked = (bool)DataBinder.Eval(row.DataItem, columnNameData);
     }
 }
Exemplo n.º 2
0
 /// <summary>
 /// Deserializes the specified object from a binary file
 /// </summary>
 public static Object Deserialize(String file, Object obj, Boolean checkValidity)
 {
     try
     {
         FileHelper.EnsureUpdatedFile(file);
         Object settings = InternalDeserialize(file, obj.GetType());
         if (checkValidity)
         {
             Object defaults = Activator.CreateInstance(obj.GetType());
             PropertyInfo[] properties = settings.GetType().GetProperties();
             foreach (PropertyInfo property in properties)
             {
                 Object current = GetValue(settings, property.Name);
                 if (current == null || (current is Color && (Color)current == Color.Empty))
                 {
                     Object value = GetValue(defaults, property.Name);
                     SetValue(settings, property.Name, value);
                 }
             }
         }
         return settings;
     }
     catch (Exception ex)
     {
         ErrorManager.ShowError(ex);
         return obj;
     }
 }
 private static ValidationResult getResult(string type, dynamic dynamicValidator, Object itemToVerify)
 {
     if (type.Contains("NoteValidator") && itemToVerify.GetType() == typeof(Note))
     {
         IValidator<Note> validator = dynamicValidator;
         return validator.Validate(itemToVerify);
     }
     else if (type.Contains("TripValidator") && itemToVerify.GetType() == typeof(Trip))
     {
         IValidator<Trip> validator = dynamicValidator;
         return validator.Validate(itemToVerify);
     }
     else if (type.Contains("POIValidator") && itemToVerify.GetType() == typeof(PointOfInterest))
     {
         IValidator<PointOfInterest> validator = dynamicValidator;
         return validator.Validate(itemToVerify);
     }
     else if (type.Contains("PhotoValidator") && itemToVerify.GetType() == typeof(Picture))
     {
         IValidator<Picture> validator = dynamicValidator;
         return validator.Validate(itemToVerify);
     }
     else
         return null;
 }
Exemplo n.º 4
0
        public override int encodeSequence(Object obj, System.IO.Stream stream, ElementInfo elementInfo)
        {
            if(!CoderUtils.isSequenceSet(elementInfo))
                return base.encodeSequence(obj, stream, elementInfo);
            else {
                int resultSize = 0;
                PropertyInfo[] fields = null;
                if (elementInfo.hasPreparedInfo())
                {
                    fields = elementInfo.getProperties(obj.GetType());
                }
                else
                {
                    SortedList<int, PropertyInfo> fieldOrder = CoderUtils.getSetOrder(obj.GetType());
                    //TO DO Performance optimization need (unnecessary copy)
                    fields = new PropertyInfo[fieldOrder.Count];
                    fieldOrder.Values.CopyTo(fields, 0);
                }

                for (int i = 0; i < fields.Length; i++)
                {
                    PropertyInfo field = fields[fields.Length - 1 - i];
                    resultSize += encodeSequenceField(obj, fields.Length - 1 - i, field, stream, elementInfo);
                }

                resultSize += encodeHeader(
                    BERCoderUtils.getTagValueForElement(
                        elementInfo,
                        TagClasses.Universal,
                        ElementType.Constructed,
                        UniversalTags.Set)
                    , resultSize, stream);
                return resultSize;
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="ob"></param>
 /// <param name="fieldPath"></param>
 /// <param name="fieldValue"></param>
 public static void modifyRecursively(Object ob, String fieldPath, String fieldValue)
 {
     if (ob == null)
     {
         return;
     }
     if (!fieldPath.Contains("."))
     {
         modifyValueOfFieldAccordingToTable(ob, fieldPath, fieldValue);
     }
     else
     {
         String prefix = fieldPath.Substring(0, fieldPath.IndexOf('.'));
         Object o;
         o = ob.GetType().GetProperty(prefix, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
         if (o != null)
         {
             PropertyInfo myProp = (PropertyInfo)o;
             Object subObject = myProp.GetValue(ob, null);
             String toPass = fieldPath.Substring(fieldPath.IndexOf('.') + 1);
             modifyRecursively(subObject, toPass, fieldValue);
         }
         else
         {
             o = ob.GetType().GetField(prefix, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
             FieldInfo myField = (FieldInfo)o;
             Object subObject = myField.GetValue(ob);
             String toPass = fieldPath.Substring(fieldPath.IndexOf('.') + 1);
             modifyRecursively(subObject, toPass, fieldValue);
         }
     }
 }
        public static Object GetPropertyValue(Object obj, String property)
        {
            try
            {
                if (property.Contains("."))
                {
                    String objProp = property.Remove(property.IndexOf("."));
                    String prop = property.Substring(property.IndexOf(".") + 1);

                    if (objProp == obj.GetType().Name)
                    {
                        return GetPropertyValue(obj, prop);
                    }
                    else
                    {
                        Object newObj = obj.GetType().GetProperty(objProp).GetValue(obj, null);
                        return GetPropertyValue(newObj, prop);
                    }
                }
                else
                {
                    return obj.GetType().GetProperty(property).GetValue(obj, null);
                }
            }
            catch (ApplicationException exc)
            {
                throw new ApplicationException(String.Format("Cannot find property: {0} ({1})", property, exc.Message));
            }
        }
Exemplo n.º 7
0
 public override void HandleEvent(Object @event)
 {
     if (@event.GetType() == typeof(ActorSpriteSetEvent))
     {
         _isAnimating = false;
         this.SetSprite(((ActorSpriteSetEvent)@event).SpriteKey);
     }
     else if (@event.GetType() == typeof(ActorFrameSetSetEvent))
     {
         _isAnimating = true;
         _frameTickCounter = 0;
         _currentFrame = 0;
         _currentAnimationSet = ((ActorFrameSetSetEvent)@event).FrameSetKey;
         var frameset = ((FrameSetResource)ResourceDictionary.GetResource(_currentAnimationSet));
         this._animationSpeed = frameset.FrameDuration;
         this.SetSprite(frameset.FrameKeys[0]);
         this._frameCount = frameset.FrameKeys.Length;
     }
     else if (@event.GetType() == typeof(ActorPropertySetEvent))
     {
         SetProperty(((ActorPropertySetEvent)@event).Property, ((ActorPropertySetEvent)@event).Value);
     }
     else if (@event.GetType() == typeof(AnimationStartedEvent))
     {
         this._currentAnimations.Add(((AnimationStartedEvent)@event).Animation);
     }            
 }
Exemplo n.º 8
0
 private static object SetObjectProperty(Context context, Object obj, String name, Object value)
 {
     if (obj is ScriptObject)
     {
         try
         {
             (obj as ScriptObject)[name] = value;
         }
         catch (Exception e)
         {
             context.RaiseNewError("System Exception: " + e.Message, context.currentNode);
         }
     }
     else
     {
         var field = obj.GetType().GetField(ScriptObject.AsString(name));
         if (field != null) field.SetValue(obj, value);
         else
         {
             var prop = obj.GetType().GetProperty(ScriptObject.AsString(name));
             if (prop != null) prop.SetValue(obj, value, null);
         }
     }
     return value;
 }
Exemplo n.º 9
0
        // Similar code exist in O2.DotNetWrappers.DotNet.Serialize
        public static bool createSerializedXmlFileFromObject(Object oObjectToProcess, String sTargetFile, Type[] extraTypes)
        {
            FileStream fileStream = null;
            try
            {
                var xnsXmlSerializerNamespaces = new XmlSerializerNamespaces();
                xnsXmlSerializerNamespaces.Add("", "");
                var xsXmlSerializer = (extraTypes != null)
                                          ? new XmlSerializer(oObjectToProcess.GetType(), extraTypes)
                                          : new XmlSerializer(oObjectToProcess.GetType());

                fileStream = new FileStream(sTargetFile, FileMode.Create);

                xsXmlSerializer.Serialize(fileStream, oObjectToProcess, xnsXmlSerializerNamespaces);
                //fileStream.Close();

                return true;
            }
            catch (Exception ex)
            {
                DI.log.ex(ex, "In createSerializedXmlStringFromObject");
                return false;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }

        }
Exemplo n.º 10
0
        public Json(Object value, MemberInfo descriptor)
        {
            if (value == null && descriptor == null) return;
            var mi = descriptor ?? (value == null ? null : value.GetType());
            var pi = mi as PropertyInfo;
            var t = mi is Type ? (Type)mi : (value == null ? null : value.GetType());

            pi.Config().Validators.ForEach(validator => validator.Validate(pi, value));
            t.Config().Validators.ForEach(validator => validator.Validate(t, value));
            // todo. after BeforeSerialize value might have become undesirably changed in-place!
            // how do we revert such changes and hydrate the object back to life?!
            value = pi.Config().Adapters.Fold(value, (curr, adapter) => adapter.BeforeSerialize(pi, curr));
            value = t.Config().Adapters.Fold(value, (curr, adapter) => adapter.BeforeSerialize(t, curr));

            if (value == null)
            {
                _my_state = State.Primitive;
                _my_primitive = null;
            }
            else if (value is Json)
            {
                _wrappee = value.AssertCast<Json>();
            }
            else
            {
                var engine = pi.Config().Engine ?? t.Config().Engine ?? (Engine)new DefaultEngine();
                if (engine is TypeEngine && !(mi is Type)) mi = mi.Type();
                _wrappee = engine.Serialize(mi, value);
            }
        }
        public void Dispatch(Object @event)
        {
            //remember to use datetime.now to set an unique value for this event.
            _logger.SetOpType("event", @event.GetType().FullName + " " + DateTime.Now.ToString());

            _logger.Info("[evt dispatcher] dispatching event " + @event.ToString());
            var eventType = @event.GetType();
            var handlerInvokerList = _domainEventHandlerCatalog.GetAllHandlerFor(eventType);
            _logger.Debug("[evt dispatcher] dispatching event " + @event.ToString() + " found " + handlerInvokerList.Count() + " handlers");
            foreach (var invoker in handlerInvokerList)
            {
                invoker.Invoke(@event as IDomainEvent);
            }
            _logger.Debug("[evt dispatcher] dispatching event " + @event.ToString() + " done");
            _logger.RemoveOpType();
            //var eventHandlerType = typeof(IDomainEventHandler<>).MakeGenericType(eventType);
            
            //var handlers = _domainEventHandlerFactory.CreateHandlers(eventHandlerType);
            //if (handlers != null)
            //{
            //    foreach (var handler in handlers)
            //    {
            //        var handlerType = handler.GetType();
            //        MethodInfo mi = handlerType.GetMethod("Handle", new[] { eventType });
            //        mi.Invoke(handler, new[] { @event });
            //    }

            //    _domainEventHandlerFactory.ReleaseHandlers(handlers);
            //}
        }
Exemplo n.º 12
0
        internal static FieldInfo GetEntityField(Object gameEntity, string fieldName)
        {
            try
            {
                FieldInfo field = gameEntity.GetType().GetField(fieldName);
                if (field == null)
                {
                    //Recurse up through the class heirarchy to try to find the field
                    Type type = gameEntity.GetType();
                    while (type != typeof(Object))
                    {
                        field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy);
                        if (field != null)
                            break;

                        type = type.BaseType;
                    }
                }
                return field;
            }
            catch (Exception ex)
            {
                LogManager.APILog.WriteLine("Failed to get entity field '" + fieldName + "'");
                if (SandboxGameAssemblyWrapper.IsDebugging)
                    LogManager.ErrorLog.WriteLine(Environment.StackTrace);
                LogManager.ErrorLog.WriteLine(ex);
                return null;
            }
        }
Exemplo n.º 13
0
        public static string ToString(Object obj)
        {
            if (obj == null) {
                return "null";
            }

            StringBuilder sb = new StringBuilder();
            PropertyInfo[] props = obj.GetType().GetProperties();

            sb.AppendLine("[" + obj.GetType().Name + "]");
            foreach (PropertyInfo prop in props) {
                if (prop.GetIndexParameters().Length == 0) {
                    sb.Append(prop.Name);
                    sb.Append(" = ");
                    sb.Append(prop.GetValue(obj, null));
                    sb.AppendLine();
                }
            }

            if (obj is IEnumerable<object>) {
                foreach (object item in (IEnumerable<object>)obj) {
                    sb.AppendLine();
                    sb.Append(ToString(item));
                }
            }

            return sb.ToString();
        }
Exemplo n.º 14
0
        public static FieldInfo GetEntityField( Object gameEntity, string fieldName, bool suppressErrors = false )
        {
            try
            {
                FieldInfo field = gameEntity.GetType( ).GetField( fieldName );
                if ( field == null )
                {
                    //Recurse up through the class heirarchy to try to find the field
                    Type type = gameEntity.GetType( );
                    while ( type != typeof( Object ) )
                    {
                        field = type.GetField( fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy );
                        if ( field != null )
                            break;

                        type = type.BaseType;
                    }
                }
                return field;
            }
            catch ( Exception ex )
            {
                if ( !suppressErrors )
                {
                    Log.Error( "Failed to get entity field '{0}'", fieldName );
                    Log.Error( ex );
                }
                return null;
            }
        }
Exemplo n.º 15
0
        public static Boolean Equals(Object a, Object b) 
        {
            if (a == null || b == null) 
            {
                return b == null && a == null;
            }

            if (a.GetType() != b.GetType()) return false;
            var propA = a.GetType().GetProperties();
            var propB = b.GetType().GetProperties();

            if (propA.Length != propB.Length) return false;

            return propA.All(p => {

                if (propertyBlackList.Contains(p.Name)) return true;

                var pinfo = propB.SingleOrDefault(pb => pb.Name == p.Name);
                if (pinfo == null) return false;

                var bvalue = pinfo.GetValue(b, null);
                var avalue = p.GetValue(a, null);
                return Object.Equals(avalue, bvalue);
            });
        }
Exemplo n.º 16
0
        public static bool IsTypeOf(Object obj, string typeFullName, bool shallow)
        {
            if (obj != null)
            {
                if (shallow)
                {
                    return obj.GetType().FullName.Equals(typeFullName);
                }
                else
                {
                    Type type = obj.GetType();
                    string fullName = type.FullName;

                    while (!fullName.Equals("System.Object"))
                    {
                        if (fullName.Equals(typeFullName))
                        {
                            return true;
                        }
                        type = type.BaseType;
                        fullName = type.FullName;
                    }
                }
            }

            return false;
        }
Exemplo n.º 17
0
        public static object UpdateContextItem(DbContext context,Object obj)
        {
            //将foreign key制空
            obj.GetType().GetProperties().ToList().ForEach(delegate (PropertyInfo pi)
            {
                var att = pi.GetCustomAttribute(typeof(ForeignKeyAttribute));
                if (att != null)
                {
                    pi.SetValue(obj, null);
                }

            });

            //修改操作为修改
            context.Entry(obj).State = EntityState.Modified;

            //重新加载foreign key的对象。
            obj.GetType().GetProperties().ToList().ForEach(delegate (PropertyInfo pi)
            {
                var att = pi.GetCustomAttribute(typeof(ForeignKeyAttribute));
                if (att != null)
                {
                    context.Entry(obj).Reference(pi.Name).Load();
                }
            });
            return obj;
        }
Exemplo n.º 18
0
        public AttributeValue(Object value)
        {
            if (value == null) return;

            //
            // FIM inconsistently returns reference values as either UniqueIdentifiers or Guids
            // To prevent repetitive checks, convert all UniqueIdentifiers to Guids,
            // and any List<UniqueIdentifier> to List<Guid>
            //
            if (value.GetType() == typeof(UniqueIdentifier)) value = ((UniqueIdentifier)value).GetGuid();
            else if (value.GetType() == typeof(List<UniqueIdentifier>))
            {
                List<Guid> guids = new List<Guid>();
                foreach (UniqueIdentifier id in (List<UniqueIdentifier>)value) guids.Add(((UniqueIdentifier)id).GetGuid());
                value = guids;
            }

            //
            // Determine if the value is a list and the base type
            //
            if (value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(List<>))
            {
                _isMultiValued = true;
                foreach (Object o in (IEnumerable)value)
                {
                    _baseType = o.GetType();
                    break;
                }
            }
            else _baseType = value.GetType();
        }
Exemplo n.º 19
0
		public static void ObjectFieldSet(Object Object, String FieldName, Object Value)
		{
			//Console.WriteLine("(" + Object + ").(" + FieldName + ")=" + Value);
			try
			{
				var Field = Object.GetType().GetField(FieldName);
				//Enum.ToObject(

				if (Field != null)
				{
					Field.SetValue(Object, ConvertTo(Value, Field.FieldType));
					return;
				}
				var Property = Object.GetType().GetProperty(FieldName);
				if (Property != null)
				{
					Property.SetValue(Object, ConvertTo(Value, Property.PropertyType), null);
					return;
				}
				throw (new NotImplementedException());
			}
			catch (Exception e)
			{
				Console.Error.WriteLine("Can't set value: " + e);
			}
		}
Exemplo n.º 20
0
        public static String createSerializedXmlStringFromObject(Object oObjectToProcess , Type[] extraTypes)
        {
            if (oObjectToProcess == null)
                DI.log.error("in createSerializedXmlStringFromObject: oObjectToProcess == null");
            else
            {
                try
                {
                    /*// handle cases file names are bigger than 220
                    if (sTargetFile.Length > 220)
                    {
                        sTargetFile = sTargetFile.Substring(0, 200) + ".xml";
                        DI.log.error("sTargetFile.Length was > 200, so renamig it to: {0}", sTargetFile);
                    }*/
                    var xnsXmlSerializerNamespaces = new XmlSerializerNamespaces();
                    xnsXmlSerializerNamespaces.Add("", "");
                    var xsXmlSerializer = (extraTypes != null)
                                              ? new XmlSerializer(oObjectToProcess.GetType(), extraTypes)
                                              : new XmlSerializer(oObjectToProcess.GetType());
                    var memoryStream = new MemoryStream();
                    xsXmlSerializer.Serialize(memoryStream, oObjectToProcess, xnsXmlSerializerNamespaces);

                    return Encoding.ASCII.GetString(memoryStream.ToArray());
                }
                catch (Exception ex)
                {
                    DI.log.ex(ex,"In createSerializedXmlStringFromObject");
                }
            }
            return "";
        }
Exemplo n.º 21
0
 public void addNode(Object node, HashTree subTree)
 {
     if (typeof(TestElement).IsAssignableFrom(node.GetType()) && !typeof(TestPlan).IsAssignableFrom(node.GetType()))
     {
         ((TestElement) node).SetRunningVersion(true);
     }
 }
            public override Object Execute(Object o, IList args)
            {
                AppDomain domain = null;
                Object remote = null;
                try
                {
                    // creating remote domain
                    domain = AppDomain.CreateDomain(o.GetType().FullName);

                    // create fixture type
                    remote = domain.CreateInstanceAndUnwrap(
                        o.GetType().Assembly.GetName().Name,
                        o.GetType().FullName
                        );

                    // run invoker on remoted type
                    return this.Invoker.Execute(remote, args);
                }
                finally
                {
                    IDisposable disposable = remote as IDisposable;
                    if (disposable!=null)
                        disposable.Dispose();
                    remote = null;
                    if (domain != null)
                    {
                        AppDomain.Unload(domain);
                    }
                }
            }
Exemplo n.º 23
0
 private static void EnsureProperty(Object source, String propertyname)
 {
     var pi = source.GetType().GetProperty(propertyname);
     if (pi == null)
     {
         throw new Exception(String.Format("Property with name '{0}' not found in type {1}", propertyname, source.GetType()));
     }
 }
Exemplo n.º 24
0
 public static DataTable ConvertToDataTable(Object source)
 {
   PropertyInfo[] properties = source.GetType().GetProperties();
   DataTable dt = CreateDataTable(properties, source);
   dt.TableName = source.GetType().Name;
   FillData(properties, dt, null, String.Empty, source);
   return dt;
 }
Exemplo n.º 25
0
 public ActionResult ReturnJson(Object obj)
 {
     if (obj.GetType() == typeof(string) || obj.GetType() == typeof(String))
     {
         return Content(obj.ToString());
     }
     return Content(JsonConvert.ObjectToJson(obj));
 }
Exemplo n.º 26
0
        public void Dispatch(Object instance, String methodName)
        {
            MethodInfo method = instance.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
            if (method == null)
                throw new AegisException("No {0} method in {1}.", methodName, instance.GetType().Name);

            method.Invoke(instance, new object[] { this });
        }
Exemplo n.º 27
0
 // Notifies a handler that an object has been unmarshaled.
 public void UnmarshaledObject(Object obj, ObjRef or)
 {
     if (obj.GetType() != typeof(AppDomain))
         Trace.WriteLine(string.Format("Tangra Addins: Unmarshaled instance of {0} ({1} HashCode:{2})", or.TypeInfo != null ? or.TypeInfo.TypeName : obj.GetType().ToString(), or.URI != null ? or.URI.ToString() : "N/A", obj.GetHashCode().ToString()));
     else
     {
         // Not interested in AppDomain marshalling
     }
 }
Exemplo n.º 28
0
 // Notifies a handler that an object has been disconnected.
 public void DisconnectedObject(Object obj)
 {
     if (obj.GetType() != typeof(AppDomain))
         Trace.WriteLine(string.Format("Tangra Addins: Disconnected instance of {0} (HashCode:{1})", obj.GetType().ToString(), obj.GetHashCode().ToString()));
     else
     {
         // Not interested in AppDomain marshalling
     }
 }
Exemplo n.º 29
0
 /// <summary>
 ///     Generates a hierarchical YAML-like string representation of an object.
 /// </summary>
 /// <param name="obj">Object to stringify.</param>
 /// <returns>Human-readable string representation of <paramref name="obj"/>.</returns>
 public static string ToString(Object obj)
 {
     var fields = obj.GetType()
                     .GetFields(BindingFlags.Instance | BindingFlags.Public)
                     .Select(member => ToString(member, member.GetValue(obj)));
     var props = obj.GetType()
                    .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                    .Select(member => ToString(member, member.GetValue(obj, new object[0])));
     return string.Join(Environment.NewLine, fields.Concat(props));
 }
Exemplo n.º 30
0
		public static PropertyInfo[] GetProperties(Object obj)
		{
			if (obj == null) return new PropertyInfo[0];
			Type objectType = obj.GetType();
			if (objectType.IsGenericType)
			{
				return obj.GetType().GetProperty("Item").PropertyType.GetProperties();
			}
			return obj.GetType().GetProperties();
		}
 //@Override
 public override bool Equals(System.Object o)
 {
     if (o == this)
     {
         return(true);
     }
     if (o == null)
     {
         return(false);
     }
     if (this.GetType().Equals(o.GetType()))
     {
         return(this.query.Equals(((MultiTermQueryWrapperFilter)o).query));
     }
     return(false);
 }
Exemplo n.º 32
0
 public override bool Equals(System.Object obj)
 {
     if (this == obj)
     {
         return(true);
     }
     if (obj == null)
     {
         return(false);
     }
     if (GetType() != obj.GetType())
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 33
0
        public static NEDataProperty[] GetProperties(System.Object obj)
        {
            List <NEDataProperty> properties = new List <NEDataProperty>();

            FieldInfo[] infos = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
            foreach (FieldInfo info in infos)
            {
                NEDatapRropertyType type = NEDatapRropertyType.Integer;
                if (NEDataProperty.GetPropertyType(info, out type))
                {
                    NEDataProperty property = new NEDataProperty(obj, info, type);
                    properties.Add(property);
                }
            }

            return(properties.ToArray());
        }
Exemplo n.º 34
0
        public static string show_item_descr(System.Data.SqlClient.SqlConnection conn, System.Web.HttpRequest req, System.Data.SqlClient.SqlTransaction tr)
        {
            SqlCommand cmd = conn.CreateCommand();

            cmd.Transaction = tr;
            cmd.CommandText = String.Format("select descr from shop_item where guididx='{0}';", req["guididx"]);
            System.Object obj   = cmd.ExecuteScalar();
            String        value = obj.GetType() == typeof(System.DBNull)?"":obj.ToString();

            string ret = String.Format(@"<div>
<form name='item_descr' action='1.axp' method='get' onsubmit='javascript:save_text({0}); return false;'>
<textarea id='HereIsTheText'> {1}</textarea></form>
</div>",
                                       "\"" + req["guididx"] + "\"", value);

            return(ret);
        }
Exemplo n.º 35
0
    public static string Status(this System.Object o)
    {
        string _s = "";

        try
        {
            string typ   = o.GetType().ToString();
            int    index = typ.LastIndexOf(".");
            _s = "  " + typ.Substring(index);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.Log(ex.ToString());
        }

        return(_s);
    }
Exemplo n.º 36
0
        static T GetBaseProperty <T>(SerializedProperty prop)
        {
            // Separate the steps it takes to get to this property
            string[] separatedPaths = prop.propertyPath.Split('.');

            // Go down to the root of this serialized property
            System.Object reflectionTarget = prop.serializedObject.targetObject as object;
            // Walk down the path to get the target object
            foreach (var path in separatedPaths)
            {
                var t = reflectionTarget.GetType();
                //with support for private types via https://gist.github.com/ChemiKhazi/11395776
                FieldInfo fieldInfo = t.GetField(path, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                reflectionTarget = fieldInfo.GetValue(reflectionTarget);
            }
            return((T)reflectionTarget);
        }
Exemplo n.º 37
0
 /// <summary>
 /// 类转换成二进制
 /// </summary>
 /// <param name="path"></param>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static bool BinarySerilize(string path, System.Object obj)
 {
     try
     {
         using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
         {
             BinaryFormatter bf = new BinaryFormatter();
             bf.Serialize(fs, obj);
         }
         return(true);
     }
     catch (Exception e)
     {
         Debug.LogError("此类无法转换成二进制 " + obj.GetType() + "," + e);
     }
     return(false);
 }
Exemplo n.º 38
0
        /// <summary> Creates a new iterator instance for the specified array.
        /// *
        /// </summary>
        /// <param name="array">The array for which an iterator is desired.
        ///
        /// </param>
        public ArrayIterator(System.Object array)
        {
            /*
             * if this isn't an array, then throw.  Note that this is
             * for internal use - so this should never happen - if it does
             *  we screwed up.
             */

            if (!array.GetType().IsArray)
            {
                throw new System.ArgumentException("Programmer error : internal ArrayIterator invoked w/o array");
            }

            this.array = array;
            pos        = 0;
            size       = ((double[])this.array).Length;
        }
Exemplo n.º 39
0
        public static object CloneFromCopyConstructor(System.Object d)
        {
            if (d != null)
            {
                Type t = d.GetType();
                foreach (ConstructorInfo ci in t.GetConstructors())
                {
                    ParameterInfo[] pi = ci.GetParameters();
                    if (pi.Length == 1 && pi[0].ParameterType == t)
                    {
                        return(ci.Invoke(new object[] { d }));
                    }
                }
            }

            return(null);
        }
Exemplo n.º 40
0
    // 初期化
    public static void Initialize()
    {
        NCMBSettings.Initialize(
            APP_KEY,
            CLIENT_KEY
            );
        CallbackFlag = false;

        GameObject o = new GameObject("settings");

        System.Object obj   = o.AddComponent <NCMBSettings> ();
        FieldInfo     field = obj.GetType().GetField("filePath", BindingFlags.Static | BindingFlags.NonPublic);

        field.SetValue(obj, Application.persistentDataPath);

        NCMBUser.LogOutAsync();
    }
Exemplo n.º 41
0
        public static List <object> RecordClassDefault(this Object obj, BindingFlags?bindingFlags)
        {
            var type       = obj.GetType();
            var fieldInfos = bindingFlags == null
                ? type.GetFilteredFieldInfos(null).ToList()
                : type.GetFilteredFieldInfos((BindingFlags)bindingFlags).ToList();

            List <object> fieldValues = new List <object>();

            foreach (var fieldInfo in fieldInfos)
            {
                fieldValues.Add(fieldInfo.GetValue(obj));
                //Debug.Log(fieldInfo.Name);
            }

            return(fieldValues);
        }
Exemplo n.º 42
0
        public override bool Equals(System.Object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return(false);
            }

            User user = (User)obj;

            return(Email.Equals(user.Email) && Address.Equals(user.Address) &&
                   Profession.Equals(user.Profession) && Privilege.Equals(user.Privilege) &&
                   Username.Equals(user.Username) && GivenName.Equals(user.GivenName) &&
                   Surname.Equals(user.Surname) && Birthdate.Equals(user.Birthdate) &&
                   Gender.Equals(user.Gender) && CultureInfo.Equals(user.CultureInfo) &&
                   City.Equals(user.City) && Country.Equals(user.Country) &&
                   Latitude.Equals(user.Latitude) && Longitude.Equals(user.Longitude));
        }
        public static KeyValuePair <object, object> CastFrom(System.Object obj)
        {
            var type = obj.GetType();

            if (type.IsGenericType)
            {
                if (type == typeof(KeyValuePair <,>))
                {
                    var key      = type.GetProperty("Key");
                    var value    = type.GetProperty("Value");
                    var keyObj   = key.GetValue(obj, null);
                    var valueObj = value.GetValue(obj, null);
                    return(new KeyValuePair <object, object>(keyObj, valueObj));
                }
            }
            throw new ArgumentException(" ### -> public static KeyValuePair<object , object > CastFrom(Object obj) : Error : obj argument must be KeyValuePair<,>");
        }
Exemplo n.º 44
0
        static T GetBaseProperty <T>(SerializedProperty prop)
        {
            // Separate the steps it takes to get to this property
            string[] separatedPaths = prop.propertyPath.Split('.');

            // Go down to the root of this serialized property
            System.Object reflectionTarget = prop.serializedObject.targetObject as object;

            // Walk down the path to get the target object
            foreach (var path in separatedPaths)
            {
                FieldInfo fieldInfo = reflectionTarget.GetType().GetField(path, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                reflectionTarget = fieldInfo.GetValue(reflectionTarget);
            }

            return((T)reflectionTarget);
        }
Exemplo n.º 45
0
        internal static void PrintObject(System.Object o, string indent = "\t")
        {
            Type   type = o.GetType();
            string init = "DEBUG: Component [" + type.Name + "] " + indent;

            Logger.Log(init + "Attributes:");
            FieldInfo[] fi = type.GetFields();
            if (fi == null || fi.Length <= 0)
            {
                Logger.Log(init + " None");
            }
            else
            {
                foreach (FieldInfo f in fi)
                {
                    string val;
                    try { val = f.GetValue(o)?.ToString(); if (val == null)
                          {
                              val = "null";
                          }
                    }
                    catch { val = "?"; }
                    Logger.Log(init + " * " + f.ToString() + " = " + val);
                }
            }
            Logger.Log(init + "Properties:");
            PropertyInfo[] pi = type.GetProperties();
            if (pi == null || pi.Length <= 0)
            {
                Logger.Log(init + " None");
            }
            else
            {
                foreach (PropertyInfo p in pi)
                {
                    string val;
                    try { val = p.GetValue(o, null)?.ToString(); if (val == null)
                          {
                              val = "null";
                          }
                    }
                    catch { val = "?"; }
                    Logger.Log(init + " * " + p.ToString() + " = " + val);
                }
            }
        }
Exemplo n.º 46
0
        /// <summary>
        /// Sets the contained item with the desired value
        /// while also checking to ensure it's a valid type
        /// </summary>
        /// <param name="newValue">The new value to assign</param>
        /// <exception cref="ArgumentException">Thrown if the newValue is
        /// not an accepted type</exception>
        public void SetValue(System.Object newValue)
        {
            if (newValue == null)
            {
                item = newValue;
                return;
            }

            Type valueType = newValue.GetType();

            if (valueType.IsSubclassOf(typeof(UnityEngine.Object)))
            {
                throw new ArgumentException("Value cannot be a unity item");
            }

            item = newValue;
        }
        /// <summary>
        /// 选中要添加的组件
        /// </summary>
        /// <param name="para"></param>
        public void ItemSelect(Object para)
        {
            if (para.GetType().Name == COMPONENT_ITEM_TYPE_NAME)
            {
                string componentName = (string)displayName.GetValue(para);
                var    gos           = Selection.gameObjects;
                foreach (var go in gos)
                {
                    Component com = go.GetComponent(componentName);
                    if (com == null)
                    {
                        Debug.LogError("can not find com ", go);
                        continue;
                    }
                    switch (componentName)
                    {
                    case ("Image"):
                    {
                        ComponentOptimizing.OptimizingImage(com as Image);
                        break;
                    }

                    case ("Text"):
                    {
                        ComponentOptimizing.OptimizingText(com as Text);
                        break;
                    }

                    case ("Mask"):
                    {
                        ComponentOptimizing.OptimizingMask(com as Mask);
                        break;
                    }

                    default:
                    {
                        Debug.Log("add " + componentName);
                        break;
                    }
                    }
                }

                isClear = false;
            }
        }
Exemplo n.º 48
0
    /// <summary>
    /// 二进制序列化
    /// </summary>
    public static bool BinarySerialize(System.Object obj)
    {
        string savePath = PathConfig.GameDataConfigBinaryPath + obj.GetType().Name + ".bytes";

        try
        {
            using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) {
                BinaryFormatter binaryF = new BinaryFormatter();
                binaryF.Serialize(fs, obj);
            }
            return(true);
        }
        catch (System.Exception e)
        {
            Debug.LogError("class to binary fail : " + e);
        }
        return(false);
    }
Exemplo n.º 49
0
    static public string toString(System.Object obj)
    {
        string result = "";

        foreach (FieldInfo fi in obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
        {
            System.Object valueObj = fi.GetValue(obj);
            if (!(valueObj is IDictionary || valueObj is IList))
            {
                result = result + fi.Name + "," + valueObj + "\n";
            }
            else
            {
                result = result + fi.Name + "," + toMiniJson(valueObj) + "\n";
            }
        }
        return(result);
    }
Exemplo n.º 50
0
        public override bool Equals(System.Object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return(false);
            }

            Edge p = (Edge)obj;

            bool value = (vertex1 == p.vertex1) && (vertex2 == p.vertex2);

            if (!value)
            {
                value = (vertex1 == p.vertex2) && (vertex2 == p.vertex1);
            }

            return(value);
        }
Exemplo n.º 51
0
        public virtual SumoColor GetColor(System.Object obj)
        {
            SumoColor output = new SumoColor(0, 0, 0, 0);

            try
            {
                if (obj.GetType().Equals(typeof(SumoColor)))
                {
                    output = (SumoColor)obj;
                }
            }
            catch (Exception ex)
            {
                MonoBehaviour.print(ex.GetBaseException());
            }

            return(output);
        }
Exemplo n.º 52
0
        public virtual double GetDouble(System.Object obj)
        {
            double output = -1;

            try
            {
                if (obj.GetType().Equals(typeof(Double)))
                {
                    output = (Double)obj;
                }
            }
            catch (Exception ex)
            {
                MonoBehaviour.print(ex.GetBaseException());
            }

            return(output);
        }
Exemplo n.º 53
0
        public virtual SumoStringList GetStringList(System.Object obj)
        {
            SumoStringList output = new SumoStringList();

            try
            {
                if (obj.GetType().Equals(typeof(SumoStringList)))
                {
                    output = (SumoStringList)obj;
                }
            }
            catch (Exception ex)
            {
                MonoBehaviour.print(ex.GetBaseException());
            }

            return(output);
        }
Exemplo n.º 54
0
        public virtual int GetInt(System.Object obj)
        {
            int output = -1;

            try
            {
                if (obj.GetType().Equals(typeof(int)))
                {
                    output = (int)obj;
                }
            }
            catch (Exception ex)
            {
                MonoBehaviour.print(ex.GetBaseException());
            }

            return(output);
        }
Exemplo n.º 55
0
        public virtual SumoGeometry GetPolygon(System.Object obj)
        {
            SumoGeometry output = new SumoGeometry();

            try
            {
                if (obj.GetType().Equals(typeof(SumoGeometry)))
                {
                    output = (SumoGeometry)obj;
                }
            }
            catch (Exception ex)
            {
                MonoBehaviour.print(ex.GetBaseException());
            }

            return(output);
        }
Exemplo n.º 56
0
        public virtual SumoTLSLogic GetTLSLogic(System.Object obj)
        {
            SumoTLSLogic output = new SumoTLSLogic(null, 0, 0, 0);

            try
            {
                if (obj.GetType().Equals(typeof(SumoTLSLogic)))
                {
                    output = (SumoTLSLogic)obj;
                }
            }
            catch (Exception ex)
            {
                MonoBehaviour.print(ex.GetBaseException());
            }

            return(output);
        }
Exemplo n.º 57
0
        public virtual string GetString(System.Object obj)
        {
            string output = "";

            try
            {
                if (obj.GetType().Equals(typeof(string)))
                {
                    output = (string)obj;
                }
            }
            catch (Exception ex)
            {
                MonoBehaviour.print(ex.GetBaseException());
            }

            return(output);
        }
Exemplo n.º 58
0
        /// <summary> Execute method against context.
        /// </summary>
        public override System.Object execute(System.Object o, InternalContextAdapter context)
        {
            if (property == null && method == null)
            {
                return(null);
            }

            try {
                if (property != null)
                {
                    return(property.GetValue(o, null));
                }
                else
                {
                    return(method.Invoke(o, new Object[0]));
                }
            } catch (System.Reflection.TargetInvocationException ite) {
                EventCartridge ec = context.EventCartridge;

                /*
                 *  if we have an event cartridge, see if it wants to veto
                 *  also, let non-Exception Throwables go...
                 */

                if (ec != null && ite.GetBaseException() is System.Exception)
                {
                    try {
                        return(ec.methodException(o.GetType(), propertyUsed, (System.Exception)ite.GetBaseException()));
                    } catch (System.Exception e) {
                        throw new MethodInvocationException("Invocation of property '" + propertyUsed + "'" + " in  " + o.GetType() + " threw exception " + ite.GetBaseException().GetType() + " : " + ite.GetBaseException().Message, ite.GetBaseException(), propertyUsed);
                    }
                }
                else
                {
                    /*
                     * no event cartridge to override. Just throw
                     */

                    throw new MethodInvocationException("Invocation of property '" + propertyUsed + "'" + " in  " + o.GetType() + " threw exception " + ite.GetBaseException().GetType() + " : " + ite.GetBaseException().Message, ite.GetBaseException(), propertyUsed);
                }
            } catch (System.ArgumentException iae) {
                return(null);
            }
        }
Exemplo n.º 59
0
 static public void dicToObject(System.Object obj, Dictionary <string, object> dict)
 {
     foreach (KeyValuePair <string, object> item in dict)
     {
         FieldInfo fi = obj.GetType().GetField(item.Key, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
         if (fi != null)
         {
             MethodInfo mi      = fi.FieldType.GetMethod("Parse", new Type[] { typeof(string) });
             string     tempStr = item.Value.ToString();
             Debug.Log(tempStr);
             System.Object value = fi.GetValue(obj);
             if (mi != null)
             {
                 fi.SetValue(obj, mi.Invoke(obj, new object[] { tempStr }));
             }
             else if (value is System.Enum)
             {
                 fi.SetValue(obj, System.Enum.Parse(fi.FieldType, tempStr));
             }
             else if (fi.FieldType == typeof(string))
             {
                 fi.SetValue(obj, tempStr);
             }
             else if (fi.FieldType == typeof(System.Collections.Generic.Dictionary <string, object>))
             {
                 fi.SetValue(obj, fromMiniJson(tempStr));
             }
             else if (fi.FieldType == typeof(System.Int32[]))
             {
                 System.Object temp = fromMiniJson(tempStr);
                 if (temp != null)
                 {
                     List <System.Object> objList = (List <System.Object>)temp;
                     List <int>           intList = new List <int>();
                     foreach (System.Object sobj in objList)
                     {
                         intList.Add(System.Convert.ToInt32(sobj));
                     }
                     fi.SetValue(obj, intList.ToArray());
                 }
             }
         }
     }
 }
Exemplo n.º 60
0
    public static FieldInfo GetFieldInfo(SerializedProperty prop)
    {
        if (prop == null)
        {
            return(null);
        }

        // Separate the steps it takes to get to this property
        string[] separatedPaths = prop.propertyPath.Split('.');

        // Go down to the root of this serialized property
        System.Object reflectionTarget = prop.serializedObject.targetObject as object;
        FieldInfo     fieldInfo        = null;

        // Walk down the path to get the target object
        for (var i = 0; i < separatedPaths.Length; i++)
        {
            var arrayIndex = -1;
            if (separatedPaths[i] == "Array")
            {
                //we get the index
                if (separatedPaths.Length > i && separatedPaths[i + 1] != null)
                {
                    arrayIndex = int.Parse(separatedPaths[i + 1].Replace("data[", "").Replace("]", ""));
                }
            }

            if (arrayIndex != -1)
            {
                i += 1;
                reflectionTarget = ((IEnumerable)reflectionTarget).Cast <object>().ToList()[arrayIndex];
            }
            else
            {
                fieldInfo = reflectionTarget.GetType().GetField(separatedPaths[i]);
                if (fieldInfo != null)
                {
                    reflectionTarget = fieldInfo.GetValue(reflectionTarget);
                }
            }
        }

        return(fieldInfo);
    }