public override void ApplyToFieldInfo(FieldInfo Info, ISerializablePacket Packet, Type Field) { if (Field.Equals(typeof(bool))) Info.SetValue(Packet, val); else Info.SetValue(Packet, Convert.ChangeType((bool)val, Info.FieldType)); }
public void Visit(string settingsNamesapce, string fieldPath, FieldInfo rawSettingsField, object rawSettings) { // Skip 'sealed' fields. if (rawSettingsField.IsDefined<SealedAttribute>()) return; if (rawSettingsField.FieldType == typeof(string)) { var originalString = (string)rawSettingsField.GetValue(rawSettings); if (originalString != null) { var expandedString = ExpandVariables(originalString, _variables); rawSettingsField.SetValue(rawSettings, expandedString); } } else if (rawSettingsField.FieldType == typeof(string[])) { string[] arr = (string[])rawSettingsField.GetValue(rawSettings); for (int i = 0; i < arr.Length; i++) { string originalString = arr[i]; if (originalString != null) { var expandedString = ExpandVariables(originalString, _variables); arr[i] = expandedString; } } } }
public override void ApplyToFieldInfo(FieldInfo Info, ISerializablePacket Packet, Type Field) { if (Field.Equals(typeof(byte[]))) Info.SetValue(Packet, val); else if(Field.Equals(typeof(string))) Info.SetValue(Packet,Marshal.ConvertToString((byte[])val)); }
public override void ApplyToFieldInfo(FieldInfo Info, ISerializablePacket Packet, Type Field) { if (Field.Equals(typeof(List<uint>))) { List<uint> Luint = new List<uint>(); foreach (ISerializableField Value in (List<ISerializableField>)val) Luint.Add(Value.GetUint()); Info.SetValue(Packet, Luint); } else if(Field.Equals(typeof(List<ISerializablePacket>))) { List<ISerializablePacket> Packets = new List<ISerializablePacket>(); foreach (ISerializableField Value in (List<ISerializableField>)val) Packets.Add(Value.GetPacket()); Info.SetValue(Packet, Packets); } else if (Field.Equals(typeof(List<bool>))) { List<bool> Bools = new List<bool>(); foreach (ISerializableField Value in (List<ISerializableField>)val) Bools.Add((bool)Value.val); Info.SetValue(Packet, Bools); } else if (Field.Equals(typeof(List<float>))) { List<float> floats = new List<float>(); foreach (ISerializableField Value in (List<ISerializableField>)val) floats.Add(Value.GetFloat()); Info.SetValue(Packet, floats); } }
public override void ApplyToFieldInfo(FieldInfo Info, ISerializablePacket Packet, Type Field) { if (Field.Equals(typeof(byte[]))) Info.SetValue(Packet, (byte[])val); else if (Field.Equals(typeof(long))) { //Array.Reverse((val as byte[])); Info.SetValue(Packet, BitConverter.ToInt64((byte[])val, 0)); } }
private void ___SetFieldValue(FieldInfo field, ConnectionStringSettings connectionStringSettings, string mapFromKey) { if (field.FieldType == typeof (ConnectionStringSettings)) { field.SetValue(this,connectionStringSettings); } else if (field.FieldType == typeof (string)) { field.SetValue(this,connectionStringSettings.ConnectionString); } else { throw new ConfigMappingException(string.Format("Connection string mappings must be either of type System.String or System.Configuration.ConnectionStringSettings. The type provided was {0}", field.FieldType.Name), mapFromKey); } }
public static void SetValue(FieldInfo fi, object obj, object val) { Type fieldType = fi.FieldType; if (typeof(INullable).IsAssignableFrom(fieldType)) val = Wrap(fieldType, val); fi.SetValue(obj, val); }
public void Visit(string settingsNamespace, string fieldPath, FieldInfo rawSettingsField, object rawSettings) { var defaultAttr = rawSettingsField.GetCustomAttribute<DefaultAttribute>(); if (defaultAttr != null) { if (!CanAssign(rawSettingsField, defaultAttr.Value)) throw new ConfigurationException("Invalid default field value for {0}.{1}: '{2}'.", rawSettingsField.DeclaringType.Name, rawSettingsField.Name, defaultAttr.Value); object targetValue = rawSettingsField.GetValue(rawSettings); if (targetValue == null) { if (rawSettingsField.FieldType == typeof(string)) rawSettingsField.SetValue(rawSettings, defaultAttr.Value.ToString()); else rawSettingsField.SetValue(rawSettings, defaultAttr.Value); } } }
public void Visit(string settingsNamesapce, string fieldPath, FieldInfo refinedSettingsField, object refinedSettings, FieldInfo rawSettingsField, object rawSettings) { if (refinedSettingsField.IsDefined<RefAttribute>()) return; object rawValue = null; object refinedValue = refinedSettingsField.GetValue(refinedSettings); if (refinedValue != null) { Type refinedValueType = refinedValue.GetType(); if (refinedValueType.IsSettingsType()) { rawValue = SettingsConstruction.CreateSettingsObject(refinedValue, rawSettingsField, _typeMappings); } else if (refinedValueType.IsSettingsOrObjectArrayType()) { rawValue = SettingsConstruction.CreateSettingsArray((Array)refinedValue, rawSettingsField, _typeMappings); } else if (refinedValueType != typeof(string) && rawSettingsField.FieldType == typeof(string)) { rawValue = ToString(refinedSettingsField, refinedSettings); } else { rawValue = refinedSettingsField.GetValue(refinedSettings); } rawSettingsField.SetValue(rawSettings, rawValue); } }
public override void Fill(Object obj, FieldInfo field) { if (CheckFillType(field)) { field.SetValue(obj, this); } }
public StepArgument(FieldInfo member, object declaringObject) { Name = member.Name; _get = () => member.GetValue(declaringObject); _set = o => member.SetValue(declaringObject, o); ArgumentType = member.FieldType; }
public override void Fill(Object obj, FieldInfo field) { if (field.FieldType is AliasParameter) { field.SetValue(obj, Data); } else { Console.WriteLine("AliasParameter.Fill: " + field.FieldType); } }
public static UserDefinedTypeImporter.SetterDelegate CreateSetter(Type type, FieldInfo field) { return (Importer importer, object value) => { var fieldValue = importer.Read(field.FieldType); field.SetValue(value, fieldValue); }; }
private void AssignElement(FieldInfo field, WatControl control) { var auto = field.GetValue(control) as AutoWatElement; if (auto == null) return; // This field is not marked with Auto var element = CreateElement(field.Name, auto, control); field.SetValue(control, element); }
public StaticCVarField(CVarAttribute attribute, FieldInfo fieldInfo) { this.Name = attribute.Name; this.Flags = attribute.Flags; this.Help = attribute.Help; fieldInfo.SetValue(null, attribute.DefaultValue); this.field = fieldInfo; }
protected void create_props(FieldInfo fi) { var m = fi.FieldType.GetConstructor(new []{typeof(VesselWrapper)}); if(m != null) { try { fi.SetValue(this, m.Invoke(new []{VSL})); } catch(Exception ex) { Log("Error while creating child props object {}:\n{}", fi.Name, ex); } } else Log("{} has no constructor {}(VesselWrapper)", fi.Name, fi.FieldType.Name); }
public InjectObjectFactoryContext(IDictionary<string, object> context) { _current = DataReference.CurrentContext(); _field = typeof(DataReference).GetField("_contextScope", BindingFlags.Static | BindingFlags.NonPublic); _field.SetValue(null, context); }
public TestDataRandomizer() { _current = DataRandomizer.Instance; _field = typeof(DataRandomizer).GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic); _field.SetValue(null, this); }
private readonly FieldInfo fieldInfo; //internal configuration field. /// <summary> /// Creates ConfigInjection instance. /// </summary> /// <param name="updateManager">UpdateManager instance to which configuration is to be injected.</param> /// <param name="configuration">The configuration for injection.</param> public ConfigInjection(DynUpdateManager updateManager, UpdateManagerConfiguration configuration) { this.updateManager = updateManager; fieldInfo = updateManager.GetType() .GetField("configuration", BindingFlags.NonPublic | BindingFlags.Instance); Assert.IsNotNull(fieldInfo); this.configuration = fieldInfo.GetValue(updateManager); fieldInfo.SetValue(updateManager, configuration); }
protected void AssignField(FieldInfo field, string value) { try{ field.SetValue (this, value); } catch(Exception ex){ Console.WriteLine("failed to set value for "+field.Name+ " ("+value+")\n"+ex.Message); } }
private void ProcessInMasterInit(FieldInfo info) { var name = info.Name; var fi = Master.GetType().GetField(name, ClassHelper.AllFlag); if (fi == null) { throw new WebException("Don't have field '{0}' in the master page", name); } object v = fi.GetValue(Master); info.SetValue(this, v); }
public static void AddToArray(FieldInfo field, object instance, object val) { if (!field.FieldType.IsArray) throw new InvalidOperationException("Field's type is not an array!"); Array c = (Array) field.GetValue(instance); ArrayList list = new ArrayList(); if (c != null) list.AddRange(c); list.Add(val); field.SetValue(instance, list.ToArray(field.FieldType.GetElementType())); }
public override void ApplyToFieldInfo(FieldInfo Info, ISerializablePacket Packet, Type Field) { if (Field.Equals(typeof(Dictionary<long, ISerializablePacket>))) { Dictionary<long, ISerializablePacket> Dic = new Dictionary<long, ISerializablePacket>(); foreach (KeyValuePair<ISerializableField, ISerializableField> KP in (val as Dictionary<ISerializableField, ISerializableField>)) { Dic.Add((long)KP.Key.GetLong(), KP.Value.GetPacket()); } Info.SetValue(Packet, Dic); } }
private void ___SetFieldValue(FieldInfo field, string mapFromKey, string value) { try { field.SetValue(this, field.FieldType.IsEnum ? Enum.Parse(field.FieldType, value, true) : Convert.ChangeType(value, field.FieldType)); } catch (Exception e) { throw new ConfigMappingException(e.Message, mapFromKey); } }
public override void ApplyToFieldInfo(FieldInfo Info, ISerializablePacket Packet, Type Field) { byte[] Data = val as byte[]; object Result = Data; if(Field.Equals(typeof(UInt32))) Result = Marshal.ConvertToUInt32(Data[3], Data[2], Data[1], Data[0]); else if(Field.Equals(typeof(Int32))) Result = BitConverter.ToInt32(Data, 0); else if(Field.Equals(typeof(long))) Result = (long)BitConverter.ToUInt32(Data,0); Info.SetValue(Packet, Result); }
public static bool CanCreateGraphData(ScriptableObject parentObject, FieldInfo fieldInfo, out GraphData graphData) { graphData = null; Type fieldValueType = fieldInfo.FieldType; if (fieldValueType.IsGenericType && (fieldValueType.GetGenericTypeDefinition() == typeof(List<>)) && typeof(ScriptableObject).IsAssignableFrom( fieldValueType.GetGenericArguments()[0])){ object[] attributes = fieldInfo.GetCustomAttributes(false); if (attributes == null || attributes.Length == 0){ return false; } GraphAttribute attribute = attributes .ToList().First((arg) => arg.GetType() == typeof(GraphAttribute)) as GraphAttribute; if (attribute != null){ object fieldValue = fieldInfo.GetValue(parentObject); if (fieldValue == null){ var newList = Activator.CreateInstance(fieldValueType); fieldInfo.SetValue(parentObject, newList); fieldValue = newList; } SerializedObject serializedObject = new SerializedObject(parentObject); graphData = new GraphData(); graphData.ItemBaseType = fieldValueType.GetGenericArguments()[0]; graphData.ItemList = fieldValue as IList; graphData.PropertyName = fieldInfo.Name; graphData.ParentObject = parentObject; graphData.SerializedItemList = serializedObject.FindProperty(fieldInfo.Name); if (string.IsNullOrEmpty(graphData.PropertyName)){ graphData.PropertyName = fieldInfo.Name; } graphData.StartNode = null; if (!string.IsNullOrEmpty(attribute.StartNode)){ graphData.StartNode = serializedObject.FindProperty(attribute.StartNode); if (graphData.StartNode == null){ Debug.LogError("Cant find property with name " + attribute.StartNode +" for this graph"); } else if (false){ //fixme through reflexion get field type graphData.StartNode = null ; Debug.LogError("Start node type is not assignable from graph node type"); } } graphData.SetDefaultStartNodeIfNothingSelected(); return true; } } return false; }
public void AssignSampleValueToField(object obj, FieldInfo fieldInfo, int? seed = null) { if (seed != null) _id = seed.Value; var childValue = fieldInfo.GetValue(obj); if (IsSimpleType(fieldInfo.FieldType)) { var value = BuildTypedSampleValue(fieldInfo.FieldType); fieldInfo.SetValue(obj, value); } else if (IsListOfSimpleType(childValue)) HandleListOfSimpleType(childValue); else ProcessCompositeChild(childValue); }
protected override void SetElement(object parent, Type parentType, FieldInfo field, string driverName) { ActionWithException(() => { var type = field.FieldType; var instance = typeof(IPage).IsAssignableFrom(type) ? GetInstancePage(parent, field, type, parentType) : GetInstanceElement(parent, type, parentType, field, driverName); instance.SetName(field); instance.Avatar.DriverName = driverName; instance.TypeName = type.Name; instance.Parent = parent; field.SetValue(parent, instance); if (typeof(IComposite).IsAssignableFrom(type)) InitElements(instance, driverName); }, ex => $"Error in setElement for field '{field.Name}' with parent '{parentType?.Name ?? "NULL Class" + ex.FromNewLine()}'"); }
void PackReferenceArray(string settingsPath, FieldInfo refinedSettingsField, object refinedSettings, FieldInfo rawSettingsField, object rawSettings) { Array settingsArray = (Array)refinedSettingsField.GetValue(refinedSettings); string references = null; if (settingsArray != null) { var wildcards = new HashSet<string>(); for (int i = 0; i < settingsArray.Length; i++) { var settings = settingsArray.GetValue(i); if (settings != null) wildcards.Add(GetSettingsWildcard(settings)); } references = String.Join(Settings.IdSeparator.ToString(), wildcards.ToArray()).TrimEnd(Settings.IdSeparator); } rawSettingsField.SetValue(rawSettings, references); }
//private readonly object _fileChangesManager; //private readonly FieldInfo _callbackFieldInfo; //private readonly FieldInfo _isFCNDisabledFieldInfo; //private readonly object _savedCallbackValue; /// <exclude /> public ShutdownGuard() { if (!HostingEnvironment.IsHosted) { return; } const BindingFlags getStaticFieldValue = BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField; _runtime = (HttpRuntime)typeof(HttpRuntime).InvokeMember("_theRuntime", getStaticFieldValue, null, null, null); _hostingEnvironment = (HostingEnvironment)typeof(HostingEnvironment).InvokeMember("_theHostingEnvironment", getStaticFieldValue, null, null, null); const BindingFlags privateField = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField; _shutdownWebEventRaised_FieldInfo = typeof(HttpRuntime).GetField("_shutdownWebEventRaised", privateField); // In .NET 3.5 the field is called "_shutdownInitated" // .NET 4.0 the field is called "_shutdownInitiated" _shutdownInitiated_FieldInfo = typeof(HostingEnvironment).GetField("_shutdownInitiated", privateField) ?? typeof(HostingEnvironment).GetField("_shutdownInitated", privateField); // Simulating situation, when all events to unload current AppDomain were already raised. _shutdownWebEventRaised_FieldInfo.SetValue(_runtime, true); _shutdownInitiated_FieldInfo.SetValue(_hostingEnvironment, true); //_fileChangesManager = runtime.GetType().GetField("_fcm", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField).GetValue(runtime); //_callbackFieldInfo = _fileChangesManager.GetType().GetField("_callbackRenameOrCriticaldirChange", // BindingFlags.NonPublic | // BindingFlags.Instance | // BindingFlags.GetField); //_isFCNDisabledFieldInfo = _fileChangesManager.GetType().GetField("_FCNMode", // BindingFlags.NonPublic | // BindingFlags.Instance | // BindingFlags.GetField); //_savedCallbackValue = _callbackFieldInfo.GetValue(_fileChangesManager); //_callbackFieldInfo.SetValue(_fileChangesManager, null); //// Turning off file change notifications. http://support.microsoft.com/kb/911272 //_isFCNDisabledFieldInfo.SetValue(_fileChangesManager, (Int32)1); }
public void Apply(UnityEngine.Object target) { if (properties == null) { return; } Type targetType = target.GetType(); foreach (Property property in properties) { System.Reflection.FieldInfo targetField = targetType.GetField(property.key); if (targetField != null) { targetField.SetValue(target, property.Value); } else { System.Reflection.PropertyInfo targetProperty = targetType.GetProperty(property.key); targetProperty.SetValue(target, property.Value); } } }
/// <summary> /// Uses a System.Reflection.FieldInfo to add a field /// Handles most built-in types and components /// includes automatic naming like the inspector does /// by default /// </summary> /// <param name="fieldInfo"></param> public static void FieldInfoField <T>(T instance, System.Reflection.FieldInfo fieldInfo) { string label = fieldInfo.Name.DeCamel(); #region Built-in Data Types if (fieldInfo.FieldType == typeof(string)) { var val = (string)fieldInfo.GetValue(instance); if (label.Contains("Path")) { Rect sfxPathRect = EditorGUILayout.GetControlRect(); // 用刚刚获取的文本输入框的位置和大小参数,创建一个文本输入框,用于输入特效路径 EditorGUI.TextField(sfxPathRect, label, val); // 判断当前鼠标正拖拽某对象或者在拖拽的过程中松开了鼠标按键 // 同时还需要判断拖拽时鼠标所在位置处于文本输入框内 if ((Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragExited) && sfxPathRect.Contains(Event.current.mousePosition)) { // 判断是否拖拽了文件 if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) { string sfxPath = DragAndDrop.paths [0]; // 拖拽的过程中,松开鼠标之后,拖拽操作结束,此时就可以使用获得的 sfxPath 变量了 if (!string.IsNullOrEmpty(sfxPath) && Event.current.type == EventType.DragExited) { DragAndDrop.AcceptDrag(); fieldInfo.SetValue(instance, common.TextUtil.cut(sfxPath, "Resources/", false, false)); } } } } else { val = EditorGUILayout.TextField(label, val); fieldInfo.SetValue(instance, val); } return; } else if (fieldInfo.FieldType == typeof(int)) { var val = (int)fieldInfo.GetValue(instance); val = EditorGUILayout.IntField(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(float)) { var val = (float)fieldInfo.GetValue(instance); val = EditorGUILayout.FloatField(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(bool)) { var val = (bool)fieldInfo.GetValue(instance); val = EditorGUILayout.Toggle(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Vector3)) { var val = (Vector3)fieldInfo.GetValue(instance); val = EditorGUILayout.Vector3Field(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Vector2)) { var val = (Vector2)fieldInfo.GetValue(instance); val = EditorGUILayout.Vector2Field(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Color)) { var val = (Color)fieldInfo.GetValue(instance); val = EditorGUILayout.ColorField(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Built-in Data Types #region Basic Unity Types else if (fieldInfo.FieldType == typeof(GameObject)) { var val = (GameObject)fieldInfo.GetValue(instance); val = ObjectField <GameObject>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Transform)) { var val = (Transform)fieldInfo.GetValue(instance); val = ObjectField <Transform>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Rigidbody)) { var val = (Rigidbody)fieldInfo.GetValue(instance); val = ObjectField <Rigidbody>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Renderer)) { var val = (Renderer)fieldInfo.GetValue(instance); val = ObjectField <Renderer>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Mesh)) { var val = (Mesh)fieldInfo.GetValue(instance); val = ObjectField <Mesh>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Sprite)) { var val = (Sprite)fieldInfo.GetValue(instance); val = ObjectField <Sprite>(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Basic Unity Types #region Unity Collider Types else if (fieldInfo.FieldType == typeof(BoxCollider)) { var val = (BoxCollider)fieldInfo.GetValue(instance); val = ObjectField <BoxCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(SphereCollider)) { var val = (SphereCollider)fieldInfo.GetValue(instance); val = ObjectField <SphereCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(CapsuleCollider)) { var val = (CapsuleCollider)fieldInfo.GetValue(instance); val = ObjectField <CapsuleCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(MeshCollider)) { var val = (MeshCollider)fieldInfo.GetValue(instance); val = ObjectField <MeshCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(WheelCollider)) { var val = (WheelCollider)fieldInfo.GetValue(instance); val = ObjectField <WheelCollider>(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Unity Collider Types #region Other Unity Types else if (fieldInfo.FieldType == typeof(CharacterController)) { var val = (CharacterController)fieldInfo.GetValue(instance); val = ObjectField <CharacterController>(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Other Unity Types }
/// 字段复制 private void SetFieldValue <T>(System.Reflection.FieldInfo sField, T sObj) where T : new() { if (sObj == null) { return; } if (sField == null) { return; } /// 数据中没有就返回 string fieldName = sField.Name; if (!_data.ContainsKey(fieldName)) { return; } try { if (sField.FieldType == typeof(string[][])) { if (_data[fieldName] == null || _data[fieldName] == "" || _data[fieldName] == "#") { sField.SetValue(sObj, null); return; } //先看是不是用#作分割 string[] arrSplit1 = _data[fieldName].Split("#".ToCharArray()); if (null != arrSplit1) { List <string[]> lstSplit2 = new List <string[]>(); for (int i = 0; i < arrSplit1.Length; i++) { //空的就不做考虑 if (string.IsNullOrEmpty(arrSplit1[i])) { continue; } //再分 string[] arrTemp = arrSplit1[i].Split("|".ToCharArray()); lstSplit2.Add(arrTemp); } if (lstSplit2.Count > 0) { //二维数组赋给二维数组 sField.SetValue(sObj, lstSplit2.ToArray()); } } return; } /// 2016.12.16 add by gus 获得数组 if (sField.FieldType == typeof(long[])) { if (_data[fieldName] == "#" || string.IsNullOrEmpty(_data[fieldName])) { sField.SetValue(sObj, new long[0]); } else { string[] valS = _data[fieldName].Split("|".ToCharArray()); long[] valL = new long[valS.Length]; for (int i = 0; i < valS.Length; i++) { if (!string.IsNullOrEmpty(valS[i])) { valL[i] = long.Parse(valS[i]); } } sField.SetValue(sObj, valL); } return; } //如果不是二维数组,直接存起来 if (sField.FieldType == typeof(string[])) { if (_data[fieldName] == null || _data[fieldName] == "" || _data[fieldName] == "#") { sField.SetValue(sObj, null); } else { sField.SetValue(sObj, _data[fieldName].Split("|".ToCharArray())); } return; } if (sField.FieldType == typeof(bool)) { sField.SetValue(sObj, _data[fieldName] == "1"); return; } if (sField.FieldType == typeof(long)) { if (_data[fieldName] == "#" || string.IsNullOrEmpty(_data[fieldName])) { sField.SetValue(sObj, (long)0); } else { sField.SetValue(sObj, long.Parse(_data[fieldName])); } return; } if (sField.FieldType == typeof(ulong)) { if (_data[fieldName] == "#" || string.IsNullOrEmpty(_data[fieldName])) { sField.SetValue(sObj, (ulong)0); } else { sField.SetValue(sObj, ulong.Parse(_data[fieldName])); } return; } if (sField.FieldType == typeof(int)) { if (_data[fieldName] == "#" || string.IsNullOrEmpty(_data[fieldName])) { sField.SetValue(sObj, 0); } else { sField.SetValue(sObj, int.Parse(_data[fieldName])); } return; } if (sField.FieldType == typeof(float)) { if (_data[fieldName] == "#" || string.IsNullOrEmpty(_data[fieldName])) { sField.SetValue(sObj, 0f); } else { sField.SetValue(sObj, float.Parse(_data[fieldName])); } return; } /// 优化内存 sField.SetValue(sObj, string.Intern(_data[fieldName])); } catch { UtilLog.LogWarning(string.Format("UtilInfoReader Set Value Error : {0}.{1} = {2}", sObj.GetType().Name, fieldName, _data[fieldName])); } }
public void SerializeX <TObject, TPropType>(TObject obj, Expression <Func <TObject, TPropType> > propertyRefExpr) where TObject : class { var expr = (MemberExpression)propertyRefExpr.Body; System.Reflection.PropertyInfo prop = expr.Member as System.Reflection.PropertyInfo; System.Reflection.FieldInfo field = null; Type underlyingType; if (prop != null) { underlyingType = prop.PropertyType; } else { field = expr.Member as System.Reflection.FieldInfo; underlyingType = field.FieldType; } if (underlyingType.IsArray) { // // Special case handling for type[] // Type elementType = underlyingType.GetElementType(); if (m_writing) { object arrayValue = (prop != null) ? prop.GetValue(obj, null) : field.GetValue(obj); SerializeOut_array(elementType, arrayValue as Array); } else { Array arrayValue = SerializeIn_array(elementType); if (typeof(TObject).IsValueType) { object objBoxed = obj; if (prop != null) { prop.SetValue(objBoxed, arrayValue, null); } else { field.SetValue(objBoxed, arrayValue); } obj = (TObject)objBoxed; } else { if (prop != null) { prop.SetValue(obj, arrayValue, null); } else { field.SetValue(obj, arrayValue); } } } return; } if (underlyingType.IsEnum) { // // Special case handling for enums // if (m_writing) { object enumValue = (prop != null) ? prop.GetValue(obj, null) : field.GetValue(obj); SerializeOut_int32(Convert.ToInt32(enumValue)); } else { Int32 intVal = SerializeIn_int32(); if (typeof(TObject).IsValueType) { object objBoxed = obj; if (prop != null) { prop.SetValue(objBoxed, Enum.ToObject(underlyingType, intVal), null); } else { field.SetValue(objBoxed, Enum.ToObject(underlyingType, intVal)); } obj = (TObject)objBoxed; } else { if (prop != null) { prop.SetValue(obj, Enum.ToObject(underlyingType, intVal), null); } else { field.SetValue(obj, Enum.ToObject(underlyingType, intVal)); } } } return; } System.Reflection.MethodInfo baseTypeMethod; if (m_serializeBaseTypeMethodLookup.TryGetValue(underlyingType, out baseTypeMethod)) { // // Fundamental/base type // if (m_writing) { object val = (prop != null) ? prop.GetValue(obj, null) : field.GetValue(obj); baseTypeMethod.Invoke(this, new object[1] { val }); } else { object val = baseTypeMethod.Invoke(this, null); if (typeof(TObject).IsValueType) { object objBoxed = obj; if (prop != null) { prop.SetValue(objBoxed, val, null); } else { field.SetValue(objBoxed, val); } obj = (TObject)objBoxed; } else { if (prop != null) { prop.SetValue(obj, val, null); } else { field.SetValue(obj, val); } } } return; } // Fallback to the generic object if (m_writing) { object val = (prop != null) ? prop.GetValue(obj, null) : field.GetValue(obj); SerializeOut_object(val); } else { // Construct the object object inValue = SerializeIn_object(underlyingType); if (typeof(TObject).IsValueType) { object objBoxed = obj; if (prop != null) { prop.SetValue(objBoxed, inValue, null); } else { field.SetValue(objBoxed, inValue); } obj = (TObject)objBoxed; } else { if (prop != null) { prop.SetValue(obj, inValue, null); } else { field.SetValue(obj, inValue); } } } }
/// <summary> /// 处理一张表 Handle A table. /// </summary> /// <param name="result">Result.</param> public static bool HandleATable(DataTable result) { Debug.Log(result.TableName); //创建这个类 Type t = Type.GetType(GetClassNameByName(result.TableName)); if (t == null) { Debug.Log("the type is null : " + result.TableName); return(false); } int columns = result.Columns.Count; int rows = result.Rows.Count; //行数从0开始 第0行为注释 int fieldsRow = 1; //字段名所在行数 int contentStarRow = 2; //内容起始行数 //获取所有字段 string[] tableFields = new string[columns]; for (int j = 0; j < columns; j++) { tableFields[j] = result.Rows[fieldsRow][j].ToString(); //Debuger.Log(tableFields[j]); } //存储表内容的字典 List <object> dataList = new List <object>(); //遍历所有内容 for (int i = contentStarRow; i < rows; i++) { object o = Activator.CreateInstance(t); for (int j = 0; j < columns; j++) { System.Reflection.FieldInfo info = o.GetType().GetField(tableFields[j]); if (info == null) { continue; } string val = result.Rows[i][j].ToString(); if (info.FieldType == typeof(int)) { info.SetValue(o, int.Parse(val)); } else if (info.FieldType == typeof(float)) { info.SetValue(o, float.Parse(val)); } else { info.SetValue(o, val); } } //o.toString(); //Debug.Log(JsonMapper.ToJson(o)); dataList.Add(o); } SaveTableData(dataList, result.TableName + GameConst.CONF_FILE_NAME); return(true); }
public void setValue(object obj, object value, object[] index) { field.SetValue(obj, value); }
static void LoadData() { //生成导表数据 string excelPath = Application.dataPath + "/Excel/"; string configPath = Application.streamingAssetsPath + "/Config/"; //获取所有的excel文件 string[] excelFiles = Directory.GetFiles(excelPath); for (int i = 0; i < excelFiles.Length; i++) { string[] fileFolders = excelFiles[i].Split('/'); string[] filenames = fileFolders[fileFolders.Length - 1].Split('.'); if (filenames[filenames.Length - 1] != "xlsx") { continue; } string filename = fileFolders[fileFolders.Length - 1]; using (FileStream fs = new FileStream(excelPath + filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (ExcelPackage excel = new ExcelPackage(fs)) { ExcelWorksheets workSheets = excel.Workbook.Worksheets; for (int j = 1; j <= workSheets.Count; j++) { ExcelWorksheet workSheet = workSheets[j]; List <object> dataList = new List <object>(); string scriptName = workSheet.Name; int lastCol = workSheet.Dimension.End.Column; int lastRow = workSheet.Dimension.End.Row; string[] tableFields = new string[lastRow]; Type t = Type.GetType(scriptName); for (int col = 0; col < lastCol; col++) { tableFields[col] = workSheet.Cells[2, col + 1].Text; } for (int row = 4; row <= lastRow; row++) { object o = Activator.CreateInstance(t); for (int col = 1; col <= lastCol; col++) { System.Reflection.FieldInfo info = o.GetType().GetField(tableFields[col - 1]); string val = workSheet.Cells[row, col].Text; if (info.FieldType == typeof(int)) { info.SetValue(o, int.Parse(val)); } else if (info.FieldType == typeof(float)) { info.SetValue(o, float.Parse(val)); } else { info.SetValue(o, val); } } dataList.Add(o); } MemoryStream memorySystem = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memorySystem, dataList);//把字典序列化成流 byte[] dictData = memorySystem.GetBuffer(); FileStream fileStream = new FileStream(configPath + scriptName + ".cfg", FileMode.Create); fileStream.Write(dictData, 0, dictData.Length); fileStream.Close(); } } } } Debug.Log("导表数据生成成功"); }
// 反射实现深拷贝 public static object DeepCopyByReflection(object obj) { if (obj == null) { return(null); } System.Object targetObj; Type targetType = obj.GetType(); // 对于值类型,直接使用=即可 if (targetType.IsValueType == true) { targetObj = obj; } else { // 对于引用类型 // 根据targetType创建引用对象 targetObj = System.Activator.CreateInstance(targetType); // 使用反射获取targetType下所有的成员 System.Reflection.MemberInfo[] memberInfos = obj.GetType().GetMembers(); // 遍历所有的成员 foreach (System.Reflection.MemberInfo member in memberInfos) { // 如果成员为字段类型:获取obj中该字段的值。 if (member.MemberType == System.Reflection.MemberTypes.Field) { System.Reflection.FieldInfo fieldInfo = (System.Reflection.FieldInfo)member; System.Object fieldValue = fieldInfo.GetValue(obj); //如果该值可直接Clone,则直接Clone;否则,递归调用DeepCopyByReflection(该值)。 if (fieldValue is ICloneable) { fieldInfo.SetValue(targetObj, (fieldValue as ICloneable).Clone()); } else { fieldInfo.SetValue(targetObj, DeepCopyByReflection(fieldValue)); } } // 如果成员为属性类型:获取obj中该属性的值。 else if (member.MemberType == System.Reflection.MemberTypes.Property) { System.Reflection.PropertyInfo propertyInfo = (System.Reflection.PropertyInfo)member; // GetSetMethod(nonPublic) nonPublic means: sIndicates whether the accessor should be returned if it is non-public. true if a non-public accessor is to be returned; otherwise, false. System.Reflection.MethodInfo methodInfo = propertyInfo.GetSetMethod(false); if (methodInfo != null) { try { // 如果该值可直接CLone,则直接Clone;否则,递归调用DeepCopyByReflection(该值)。 object propertyValue = propertyInfo.GetValue(obj, null); if (propertyValue is ICloneable) { propertyInfo.SetValue(targetObj, (propertyValue as ICloneable).Clone(), null); } else { propertyInfo.SetValue(targetObj, DeepCopyByReflection(propertyValue), null); } } catch (Exception e) { // some thing except. Debug.Log(e.Message); } } } } } return(targetObj); }
void createField <T>(System.Reflection.FieldInfo itemvar, T data, int id, ref IList list, int showName = -1) { if (itemvar.IsStatic) { return; } // if (datas[selectedData].getFieldOptions(itemvar.Name).show == false) return; string name = itemvar.Name; if (showName != -1) { name = showName.ToString() + " " + itemvar.FieldType.Name; } object value = itemvar.GetValue(data); if (value == null) { //Debug.Log(itemvar); value = initVoidValue(itemvar, value); //Debug.Log(itemvar + " -2- " + value); //Debug.Log(value); if (value == null) { return; } } GUILayout.BeginHorizontal(); if (itemvar.FieldType.IsGenericType && itemvar.FieldType.GetGenericTypeDefinition() == typeof(List <>)) { object objRef = list[id]; if (itemvar.FieldType.GetGenericArguments()[0] == typeof(string)) { createFieldListString(name, ref value, false, getTypeReference(itemvar), getRefenrece(itemvar)); } else { createFieldtList(name, ref value, false); } // Debug.Log((value as IList).Count); try { itemvar.SetValue(objRef, value); list[id] = (T)objRef; } catch { } } else if (itemvar.FieldType.IsArray) { //createFieldtList(itemvar.Name, value, id, ref list); object objRef = list[id]; if (itemvar.FieldType.GetElementType() == typeof(string)) { createFieldListString(name, ref value, true, getTypeReference(itemvar), getRefenrece(itemvar)); string[] s = new string[(value as List <string>).Count]; for (int i = 0; i < s.Length; i++) { s[i] = (value as List <string>)[i]; } itemvar.SetValue(objRef, s); //Debug.Log(value); } else { createFieldtList(name, ref value, true); itemvar.SetValue(objRef, value); } list[id] = (T)objRef; } else { GUILayout.Label(name, GUILayout.Width(100)); object objRef = list[id]; if (itemvar.FieldType.IsClass && itemvar.FieldType != typeof(string)) { createClassField(itemvar, value); itemvar.SetValue(objRef, value); } else if (itemvar.FieldType.IsEnum) { System.Enum es = (System.Enum)value; es = EditorGUILayout.EnumPopup(es, GUILayout.Width(100)); itemvar.SetValue(objRef, es); } else if (!createGenericField(itemvar, value, objRef)) { //object r = itemvar.GetValue(objRef); createClassField(itemvar, value); itemvar.SetValue(objRef, value); } list[id] = (T)objRef; } GUILayout.EndHorizontal(); }
public void Load(string txt) { TinyXmlReader reader = new TinyXmlReader(txt); while (reader.Read()) { string objectName = typeof(T).Name; if (reader.tagName == objectName && reader.isOpeningTag) { T data = new T(); while (reader.Read()) { if (reader.isOpeningTag && reader.tagName != objectName) { string fieldName = reader.tagName; System.Reflection.FieldInfo fieldInfo = typeof(T).GetField(fieldName); if (fieldInfo != null) { if (fieldInfo.FieldType == typeof(int)) { fieldInfo.SetValue(data, int.Parse(reader.content)); } else if (fieldInfo.FieldType == typeof(float)) { fieldInfo.SetValue(data, float.Parse(reader.content)); } else if (fieldInfo.FieldType == typeof(string)) { fieldInfo.SetValue(data, reader.content); } else if (fieldInfo.FieldType == typeof(bool)) { fieldInfo.SetValue(data, bool.Parse(reader.content)); } else if (fieldInfo.FieldType == typeof(int[])) { List <int> value = new List <int>(); while (reader.Read()) { if (reader.tagName == "int" && reader.isOpeningTag) { value.Add(int.Parse(reader.content)); } else if (reader.tagName == fieldName && reader.isOpeningTag == false) { fieldInfo.SetValue(data, value.ToArray()); goto ONEOBJ; } } } else if (fieldInfo.FieldType == typeof(float[])) { List <float> value = new List <float>(); while (reader.Read()) { if (reader.tagName == "float" && reader.isOpeningTag) { value.Add(float.Parse(reader.content)); } else if (reader.tagName == fieldName && reader.isOpeningTag == false) { fieldInfo.SetValue(data, value.ToArray()); goto ONEOBJ; } } } else if (fieldInfo.FieldType == typeof(string[])) { List <string> value = new List <string>(); while (reader.Read()) { if (reader.tagName == "string" && reader.isOpeningTag) { value.Add(reader.content); } else if (reader.tagName == fieldName && reader.isOpeningTag == false) { fieldInfo.SetValue(data, value.ToArray()); goto ONEOBJ; } } } else if (fieldInfo.FieldType == typeof(List <string>)) { List <string> value = new List <string>(); while (reader.Read()) { if (reader.tagName == "string" && reader.isOpeningTag) { value.Add(reader.content); } else if (reader.tagName == fieldName && reader.isOpeningTag == false) { fieldInfo.SetValue(data, value); goto ONEOBJ; } } } else if (fieldInfo.FieldType == typeof(List <int>)) { List <int> value = new List <int>(); while (reader.Read()) { if (reader.tagName == "int" && reader.isOpeningTag) { value.Add(int.Parse(reader.content)); } else if (reader.tagName == fieldName && reader.isOpeningTag == false) { fieldInfo.SetValue(data, value); goto ONEOBJ; } } } else if (fieldInfo.FieldType == typeof(List <float>)) { List <float> value = new List <float>(); while (reader.Read()) { if (reader.tagName == "float" && reader.isOpeningTag) { value.Add(float.Parse(reader.content)); } else if (reader.tagName == fieldName && reader.isOpeningTag == false) { fieldInfo.SetValue(data, value); goto ONEOBJ; } } } } } ONEOBJ: if (reader.tagName == objectName && reader.isOpeningTag == false) { break; } } Add(data); } } OnLoaded(); }
/// <summary> /// Set the value of one property of this object. /// </summary> /// <param name="name">Name of the field to be set.</param> /// <param name="value">String representation of the value of the field.</param> /// <returns>True of the field could be set with the given value. False if there is no field with the given name.</returns> public bool setSetting(string name, string value) { // Replace '-' in ml settings name with underscore since '-' isnt a valid symbol for names. // Now both underscore and '-' are supported for uniform naming. if (name.Contains("-")) { name = name.Replace("-", "_"); } System.Reflection.FieldInfo fi = this.GetType().GetField(name); if (fi == null) { return(false); } string asa = fi.FieldType.FullName; // The processing of the blacklist if (name.ToLower().Equals("blacklisted")) { String[] optionsToBlacklist = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (String option in optionsToBlacklist) { this.blacklisted.Add(option.ToLower()); } this.blacklisted = this.blacklisted.Distinct().ToList(); return(true); } if (fi.FieldType.FullName.Equals("System.Boolean")) { if (value.ToLowerInvariant() == "true" || value.ToLowerInvariant() == "false") { fi.SetValue(this, Convert.ToBoolean(value)); return(true); } else { return(false); } } if (fi.FieldType.FullName.Equals("System.Int32")) { int n; bool isNumeric = int.TryParse(value, out n); if (isNumeric) { fi.SetValue(this, n); return(true); } else { return(false); } } if (fi.FieldType.FullName.Equals("System.Int64")) { int n; bool isNumeric = int.TryParse(value, out n); if (isNumeric) { fi.SetValue(this, n); return(true); } else { return(false); } } if (fi.FieldType.FullName.Equals("MachineLearning.Learning.ML_Settings+LossFunction")) { if (value.Equals("RELATIVE")) { fi.SetValue(this, LossFunction.RELATIVE); return(true); } if (value.Equals("LEASTSQUARES")) { fi.SetValue(this, LossFunction.LEASTSQUARES); return(true); } if (value.Equals("ABSOLUTE")) { fi.SetValue(this, LossFunction.ABSOLUTE); return(true); } } if (fi.FieldType.FullName.Equals("System.Double")) { double n; bool isNumeric = double.TryParse(value, out n); if (isNumeric) { fi.SetValue(this, n); return(true); } else { return(false); } } if (fi.FieldType.FullName.Equals("System.TimeSpan")) { TimeSpan n; bool isValid = TimeSpan.TryParse(value, out n); if (isValid) { fi.SetValue(this, n); return(true); } else { return(false); } } if (fi.FieldType.FullName.Equals("MachineLearning.Learning.ML_Settings+ScoreMeasure")) { ScoreMeasure parsedValue; try { parsedValue = (ScoreMeasure)Enum.Parse(typeof(ScoreMeasure), value.ToUpperInvariant()); } catch (ArgumentException) { return(false); } fi.SetValue(this, parsedValue); return(true); } return(false); }
/// <summary> /// Enables to set the value of a private field with given name. /// </summary> private void SetPrivateField <T, U>(T obj, string fieldName, U value) { System.Reflection.FieldInfo info = obj.GetType().GetField(fieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); info.SetValue(obj, value); }
void ResetData(Data key, GameObject go) { System.Reflection.FieldInfo f = A.Field <GameController>(A.GC, key.ToString()); Type type = GameController.Datas[key].GetType(); if (go.name == "ColorPicker") { f.SetValue(A.GC, go.Gc <ColorPicker>().Color = key.Col()); } else if (go.name == "Dropdown") { f.SetValue(A.GC, go.Gc <Dropdown>().value = key.I()); } else if (go.name == "InputField") { InputField inputField = go.Gc <InputField>(); if (type == typeof(float)) { f.SetValue(A.GC, GetValSetInp <float>(inputField, key)); } else if (type == typeof(int)) { f.SetValue(A.GC, GetValSetInp <int>(inputField, key)); } else if (type == typeof(string)) { f.SetValue(A.GC, GetValSetInp <string>(inputField, key)); } } else if (go.name == "Slider") { f.SetValue(A.GC, go.Gc <Slider>().value = key.F()); } else if (go.name == "Toggle") { f.SetValue(A.GC, go.Gc <Toggle>().isOn = key.B()); } else if (go.name == "Vector") { if (type == typeof(Vector2)) { Vector2 v = key.V2(); SetVecGo(go, v.x, v.y); f.SetValue(A.GC, v); } else if (type == typeof(Vector2Int)) { Vector2Int v = key.V2I(); SetVecGo(go, v.x, v.y); f.SetValue(A.GC, v); } else if (type == typeof(Vector3)) { Vector3 v = key.V3(); SetVecGo(go, v.x, v.y, v.z); f.SetValue(A.GC, v); } else if (type == typeof(Vector3Int)) { Vector3Int v = key.V3I(); SetVecGo(go, v.x, v.y, v.z); f.SetValue(A.GC, v); } else if (type == typeof(Vector4)) { Vector4 v = key.V4(); SetVecGo(go, v.x, v.y, v.z, v.w); f.SetValue(A.GC, v); } } }
/// <summary> /// Executes in-line markup /// 3 possible markups: /// -set any field name on Dialogue System to a float. Ex: [textSpeed=0.5] /// -execute single word command. Ex: [slow] /// -reset commands Ex: [/slow] /// </summary> /// <param name="s">Command string</param> private void ExecuteMarkUp(string s) { var words = s.Split('='); //if syntax includes setting a variable equal to a value, then attempt to do so if (words.Length == 2) { //searches variables in this object to see if one matches the name given System.Reflection.FieldInfo fieldName = this.GetType().GetField(words[0]); if (fieldName != null) { if (float.TryParse(words[1], out float value)) { fieldName.SetValue(this, value); } else { Debug.LogWarning("field- " + words[0] + " not set to valid float"); } } else { Debug.LogWarning("Field name not found: " + words[0]); } } else { bool stopCommand = false; if (s.Contains("/")) { words = s.Split('/'); if (words.Length != 2) { Debug.LogWarning("Invalid markup : " + s + " - too many slashes"); } stopCommand = true; s = words[1]; } /* we could do this without a switch statement by either using a hashtable * or by using other functions that would be called via reflection. * but this is easiest for now. */ switch (s) { case "slow": if (stopCommand) { textSpeed = textSpeedDefault; } else { textSpeed = textSpeedSlow; } break; case "pause": textPaused = true; break; default: Debug.LogWarning("markup not recognized: " + s); break; } } }
/// <summary> /// Uses a System.Reflection.FieldInfo to add a field /// Handles most built-in types and components /// includes automatic naming like the inspector does /// by default /// </summary> /// <param name="fieldInfo"></param> public static void FieldInfoField <T>(T instance, System.Reflection.FieldInfo fieldInfo) { string label = fieldInfo.Name.DeCamel(); #region Built-in Data Types if (fieldInfo.FieldType == typeof(string)) { var val = (string)fieldInfo.GetValue(instance); val = EditorGUILayout.TextField(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(int)) { var val = (int)fieldInfo.GetValue(instance); val = EditorGUILayout.IntField(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(float)) { var val = (float)fieldInfo.GetValue(instance); val = EditorGUILayout.FloatField(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(bool)) { var val = (bool)fieldInfo.GetValue(instance); val = EditorGUILayout.Toggle(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Built-in Data Types #region Basic Unity Types else if (fieldInfo.FieldType == typeof(GameObject)) { var val = (GameObject)fieldInfo.GetValue(instance); val = ObjectField <GameObject>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Transform)) { var val = (Transform)fieldInfo.GetValue(instance); val = ObjectField <Transform>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Rigidbody)) { var val = (Rigidbody)fieldInfo.GetValue(instance); val = ObjectField <Rigidbody>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Renderer)) { var val = (Renderer)fieldInfo.GetValue(instance); val = ObjectField <Renderer>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Mesh)) { var val = (Mesh)fieldInfo.GetValue(instance); val = ObjectField <Mesh>(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Basic Unity Types #region Unity Collider Types else if (fieldInfo.FieldType == typeof(BoxCollider)) { var val = (BoxCollider)fieldInfo.GetValue(instance); val = ObjectField <BoxCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(SphereCollider)) { var val = (SphereCollider)fieldInfo.GetValue(instance); val = ObjectField <SphereCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(CapsuleCollider)) { var val = (CapsuleCollider)fieldInfo.GetValue(instance); val = ObjectField <CapsuleCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(MeshCollider)) { var val = (MeshCollider)fieldInfo.GetValue(instance); val = ObjectField <MeshCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(WheelCollider)) { var val = (WheelCollider)fieldInfo.GetValue(instance); val = ObjectField <WheelCollider>(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Unity Collider Types #region Other Unity Types else if (fieldInfo.FieldType == typeof(CharacterController)) { var val = (CharacterController)fieldInfo.GetValue(instance); val = ObjectField <CharacterController>(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Other Unity Types }
void IProperty.SetValue(object obj, object val, object[] index) { FieldInfo.SetValue(obj, val); }
void SaveData(Data key, GameObject go) { System.Reflection.FieldInfo f = A.Field <GameController>(A.GC, key.ToString()); Type type = GameController.Datas[key].GetType(); if (go.name == "ColorPicker") { f.SetValue(A.GC, go.Gc <ColorPicker>().Color); } else if (go.name == "Dropdown") { f.SetValue(A.GC, go.Gc <Dropdown>().value); } else if (go.name == "InputField") { string text = go.Gc <InputField>().text; if (type == typeof(int)) { f.SetValue(A.GC, text.I()); } else if (type == typeof(float)) { f.SetValue(A.GC, text.F()); } else if (type == typeof(string)) { f.SetValue(A.GC, text); } } else if (go.name == "Slider") { f.SetValue(A.GC, go.Gc <Slider>().value); } else if (go.name == "Toggle") { f.SetValue(A.GC, go.Gc <Toggle>().isOn); } else if (go.name == "Vector") { if (type == typeof(Vector2)) { f.SetValue(A.GC, new Vector2(InpVal(go, 0), InpVal(go, 1))); } else if (type == typeof(Vector2Int)) { f.SetValue(A.GC, new Vector2(InpVal(go, 0), InpVal(go, 1)).V2I()); } else if (type == typeof(Vector3)) { f.SetValue(A.GC, new Vector3(InpVal(go, 0), InpVal(go, 1), InpVal(go, 2))); } else if (type == typeof(Vector3Int)) { f.SetValue(A.GC, new Vector3(InpVal(go, 0), InpVal(go, 1), InpVal(go, 2)).V3I()); } else if (type == typeof(Vector4)) { f.SetValue(A.GC, new Vector4(InpVal(go, 0), InpVal(go, 1), InpVal(go, 2), InpVal(go, 3))); } } key.Set(f.GetValue(A.GC)); }
void LoadData(string TableName) { Table = TableName; TextAsset asset = Resources.Load <TextAsset>(TableName); if (asset == null) { return; } string[] lines = asset.text.Split(new string[] { "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries); if (lines.Length <= 2) { return; } bool findName = false; List <string> fieldIdenity = new List <string>(); string[] eachline = lines[1].Split(new char[] { '\t' }); for (int i = 0; i < eachline.Length; i++) { fieldIdenity.Add(eachline[i]); //if (eachline[i] == "Name") // findName = true; } int idx = -1; string Name = ""; for (int i = 2; i < lines.Length; i++) { row = i + 1; eachline = lines[i].Split(new char[] { '\t' }); T obj = System.Activator.CreateInstance <T>(); bool emptyRow = false; for (int j = 0; j < eachline.Length; j++) { col = j + 1; System.Reflection.FieldInfo field = typeof(T).GetField(fieldIdenity[j]); if (j == 0 && fieldIdenity[0].Equals("Idx")) { if (eachline[j] == "") { emptyRow = true; break; } idx = int.Parse(eachline[j]); } if (field != null) { if (field.FieldType == typeof(int)) { field.SetValue(obj, eachline[j] == "" ? 0 : int.Parse(eachline[j])); } else if (field.FieldType == typeof(uint)) { field.SetValue(obj, eachline[j] == "" ? 0 : uint.Parse(eachline[j])); } else if (field.FieldType == typeof(float)) { field.SetValue(obj, eachline[j] == "" ? 0 : float.Parse(eachline[j])); } else if (field.FieldType == typeof(string)) { field.SetValue(obj, eachline[j]); if (findName && field.Name.Equals("Name")) { Name = eachline[j]; } } else if (field.FieldType == typeof(Vector3)) { string strv = eachline[j].Trim(new char[] { '\"' }); string[] pos = strv.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries); if (pos.Length == 3) { Vector3 vec = new Vector3(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2])); field.SetValue(obj, vec); } } else { Debug.LogWarning("错误的成员类型,需要手动在此增加其处理."); } } } if (emptyRow) { continue; } //if (findName && !string.IsNullOrEmpty(Name)) //{ // if (StrValues.ContainsKey(Name)) // Debug.LogWarning("tbl: " + TableName + " 包含不唯一的 Name行:" + idx); // StrValues[Name] = obj; //} tblMap.Add(idx, obj); } }
public static PackedMemorySnapshot LoadSnapshotBin(Stream stream) { System.Reflection.ConstructorInfo ci = typeof(PackedMemorySnapshot).GetConstructor(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, null, new Type[0], new System.Reflection.ParameterModifier[0]); PackedMemorySnapshot packed = ci.Invoke(null) as PackedMemorySnapshot; BinaryReader br = new BinaryReader(stream); stream.Position += 8; MemUtil.LoadSnapshotProgress(0, "Loading Connection"); float prog = 0; float lastProg = 0; var len = br.ReadInt32(); var connctions = new Connection[len]; System.Reflection.FieldInfo fi = typeof(PackedMemorySnapshot).GetField("m_Connections", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); fi.SetValue(packed, connctions); for (int i = 0; i < len; i++) { Connection c = new Connection(); c.from = br.ReadInt32(); c.to = br.ReadInt32(); prog = ((float)i / len) * 0.15f; if (prog - lastProg > 0.01) { MemUtil.LoadSnapshotProgress(prog, string.Format("Loading Connction {0}/{1}", i + 1, len)); lastProg = prog; } connctions[i] = c; } len = br.ReadInt32(); PackedGCHandle[] handles = new PackedGCHandle[len]; fi = typeof(PackedMemorySnapshot).GetField("m_GcHandles", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); fi.SetValue(packed, handles); System.Reflection.FieldInfo[] fis = new System.Reflection.FieldInfo[] { typeof(PackedGCHandle).GetField("m_Target", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) }; for (int i = 0; i < len; i++) { object h = new PackedGCHandle(); var target = br.ReadUInt64(); fi = fis[0]; fi.SetValue(h, target); prog = 0.15f + ((float)i / len) * 0.15f; if (prog - lastProg > 0.01) { MemUtil.LoadSnapshotProgress(prog, string.Format("Loading GCHandles {0}/{1}", i + 1, len)); lastProg = prog; } handles[i] = (PackedGCHandle)h; } len = br.ReadInt32(); MemorySection[] managedHeap = new MemorySection[len]; fi = typeof(PackedMemorySnapshot).GetField("m_ManagedHeapSections", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); fi.SetValue(packed, managedHeap); fis = new System.Reflection.FieldInfo[] { typeof(MemorySection).GetField("m_Bytes", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(MemorySection).GetField("m_StartAddress", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) }; for (int i = 0; i < len; i++) { object h = new MemorySection(); var bLen = br.ReadInt32(); var bytes = br.ReadBytes(bLen); var startAddress = br.ReadUInt64(); fi = fis[0]; fi.SetValue(h, bytes); fi = fis[1]; fi.SetValue(h, startAddress); prog = 0.3f + ((float)i / len) * 0.15f; if (prog - lastProg > 0.01) { MemUtil.LoadSnapshotProgress(prog, string.Format("Loading Managed Heap {0}/{1}", i + 1, len)); lastProg = prog; } managedHeap[i] = (MemorySection)h; if (managedHeap[i].bytes == null) { UnityEngine.Debug.Log("ff"); } } len = br.ReadInt32(); PackedNativeUnityEngineObject[] nativeObj = new PackedNativeUnityEngineObject[len]; fi = typeof(PackedMemorySnapshot).GetField("m_NativeObjects", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); fi.SetValue(packed, nativeObj); fis = new System.Reflection.FieldInfo[] { typeof(PackedNativeUnityEngineObject).GetField("m_ClassId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(PackedNativeUnityEngineObject).GetField("m_HideFlags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(PackedNativeUnityEngineObject).GetField("m_InstanceId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(PackedNativeUnityEngineObject).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(PackedNativeUnityEngineObject).GetField("m_Name", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(PackedNativeUnityEngineObject).GetField("m_NativeObjectAddress", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(PackedNativeUnityEngineObject).GetField("m_Size", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) }; for (int i = 0; i < len; i++) { object obj = new PackedNativeUnityEngineObject(); int clsID = br.ReadInt32(); HideFlags hideFlags = (HideFlags)br.ReadByte(); int instanceID = br.ReadInt32(); var ft = typeof(PackedNativeUnityEngineObject).GetNestedType("ObjectFlags", System.Reflection.BindingFlags.NonPublic); int flags = 0; if (br.ReadBoolean()) { flags |= 1; } if (br.ReadBoolean()) { flags |= 4; } if (br.ReadBoolean()) { flags |= 2; } object flag = Enum.ToObject(ft, flags); string name = null; if (br.ReadBoolean()) { name = br.ReadString(); } long nativeAddress = br.ReadInt64(); int size = br.ReadInt32(); fi = fis[0]; fi.SetValue(obj, clsID); fi = fis[1]; fi.SetValue(obj, hideFlags); fi = fis[2]; fi.SetValue(obj, instanceID); fi = fis[3]; fi.SetValue(obj, flag); fi = fis[4]; fi.SetValue(obj, name); fi = fis[5]; fi.SetValue(obj, nativeAddress); fi = fis[6]; fi.SetValue(obj, size); prog = 0.45f + ((float)i / len) * 0.15f; if (prog - lastProg > 0.01) { MemUtil.LoadSnapshotProgress(prog, string.Format("Loading Native Objects {0}/{1}", i + 1, len)); lastProg = prog; } nativeObj[i] = (PackedNativeUnityEngineObject)obj; } len = br.ReadInt32(); PackedNativeType[] nativeTypes = new PackedNativeType[len]; fi = typeof(PackedMemorySnapshot).GetField("m_NativeTypes", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); fi.SetValue(packed, nativeTypes); fis = new System.Reflection.FieldInfo[] { typeof(PackedNativeType).GetField("m_BaseClassId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(PackedNativeType).GetField("m_Name", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) }; for (int i = 0; i < len; i++) { object t = new PackedNativeType(); int baseClassId = br.ReadInt32(); string name = null; if (br.ReadBoolean()) { name = br.ReadString(); } fi = fis[0]; fi.SetValue(t, baseClassId); fi = fis[1]; fi.SetValue(t, name); prog = 0.6f + ((float)i / len) * 0.15f; if (prog - lastProg > 0.01) { MemUtil.LoadSnapshotProgress(prog, string.Format("Loading Native Types {0}/{1}", i + 1, len)); lastProg = prog; } nativeTypes[i] = (PackedNativeType)t; } len = br.ReadInt32(); TypeDescription[] typeDesc = new TypeDescription[len]; fi = typeof(PackedMemorySnapshot).GetField("m_TypeDescriptions", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); fi.SetValue(packed, typeDesc); fis = new System.Reflection.FieldInfo[] { typeof(TypeDescription).GetField("m_Assembly", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(TypeDescription).GetField("m_BaseOrElementTypeIndex", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(TypeDescription).GetField("m_Fields", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(TypeDescription).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(TypeDescription).GetField("m_Name", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(TypeDescription).GetField("m_Size", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(TypeDescription).GetField("m_StaticFieldBytes", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(TypeDescription).GetField("m_TypeIndex", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(TypeDescription).GetField("m_TypeInfoAddress", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), }; var fis2 = new System.Reflection.FieldInfo[] { typeof(FieldDescription).GetField("m_IsStatic", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(FieldDescription).GetField("m_Name", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(FieldDescription).GetField("m_Offset", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(FieldDescription).GetField("m_TypeIndex", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), }; for (int i = 0; i < len; i++) { object t = new TypeDescription(); int flags = br.ReadInt32() << 0x10; string assembly = br.ReadString(); int baseOrElementTypeIndex = br.ReadInt32(); int fLen = br.ReadInt32(); FieldDescription[] fields = new FieldDescription[fLen]; for (int j = 0; j < fLen; j++) { object f = new FieldDescription(); bool isStatic = br.ReadBoolean(); string fname = br.ReadString(); int offset = br.ReadInt32(); int ftypeIndex = br.ReadInt32(); fi = fis2[0]; fi.SetValue(f, isStatic); fi = fis2[1]; fi.SetValue(f, fname); fi = fis2[2]; fi.SetValue(f, offset); fi = fis2[3]; fi.SetValue(f, ftypeIndex); fields[j] = (FieldDescription)f; } if (br.ReadBoolean()) { flags |= 2; } if (br.ReadBoolean()) { flags |= 1; } string name = br.ReadString(); int size = br.ReadInt32(); byte[] staticField = br.ReadBytes(br.ReadInt32()); int typeIndex = br.ReadInt32(); ulong typeAddress = br.ReadUInt64(); fi = fis[0]; fi.SetValue(t, assembly); fi = fis[1]; fi.SetValue(t, baseOrElementTypeIndex); fi = fis[2]; fi.SetValue(t, fields); fi = fis[3]; fi.SetValue(t, Enum.ToObject(typeof(TypeDescription).GetNestedType("TypeFlags", System.Reflection.BindingFlags.NonPublic), flags)); fi = fis[4]; fi.SetValue(t, name); fi = fis[5]; fi.SetValue(t, size); fi = fis[6]; fi.SetValue(t, staticField); fi = fis[7]; fi.SetValue(t, typeIndex); fi = fis[8]; fi.SetValue(t, typeAddress); prog = 0.75f + ((float)i / len) * 0.15f; if (prog - lastProg > 0.01) { MemUtil.LoadSnapshotProgress(prog, string.Format("Loading Type Definitions {0}/{1}", i + 1, len)); lastProg = prog; } typeDesc[i] = (TypeDescription)t; } object vminfo = new VirtualMachineInformation(); fis = new System.Reflection.FieldInfo[] { typeof(VirtualMachineInformation).GetField("m_AllocationGranularity", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(VirtualMachineInformation).GetField("m_ArrayBoundsOffsetInHeader", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(VirtualMachineInformation).GetField("m_ArrayHeaderSize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(VirtualMachineInformation).GetField("m_ArraySizeOffsetInHeader", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(VirtualMachineInformation).GetField("m_ObjectHeaderSize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), typeof(VirtualMachineInformation).GetField("m_PointerSize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic), }; fis[0].SetValue(vminfo, br.ReadInt32()); fis[1].SetValue(vminfo, br.ReadInt32()); fis[2].SetValue(vminfo, br.ReadInt32()); fis[3].SetValue(vminfo, br.ReadInt32()); int version = br.ReadInt32(); fis[4].SetValue(vminfo, br.ReadInt32()); fis[5].SetValue(vminfo, br.ReadInt32()); fi = typeof(PackedMemorySnapshot).GetField("m_VirtualMachineInformation", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); fi.SetValue(packed, vminfo); MemUtil.LoadSnapshotProgress(1f, "done"); return(packed); }
public static void SetValue(this SerializedProperty property, object value) { System.Type parentType = property.serializedObject.targetObject.GetType(); System.Reflection.FieldInfo fi = parentType.GetField(property.propertyPath);//this FieldInfo contains the type. fi.SetValue(property.serializedObject.targetObject, value); }