System.Type.GetField(string)

Here are the examples of the csharp api System.Type.GetField(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1381 Examples 7

19 View Source File : Opcode.cs
License : MIT License
Project Creator : AlexGyver

public static void Open() {  
      int p = (int)Environment.OSVersion.Platform;
            
      byte[] rdtscCode;
      byte[] cpuidCode;
      if (IntPtr.Size == 4) {
        rdtscCode = RDTSC_32;
        cpuidCode = CPUID_32;
      } else {
        rdtscCode = RDTSC_64;
        
        if ((p == 4) || (p == 128)) { // Unix
          cpuidCode = CPUID_64_LINUX;
        } else { // Windows
          cpuidCode = CPUID_64_WINDOWS;
        }
      }
      
      size = (ulong)(rdtscCode.Length + cpuidCode.Length);

      if ((p == 4) || (p == 128)) { // Unix   
        replacedembly replacedembly = 
          replacedembly.Load("Mono.Posix, Version=2.0.0.0, Culture=neutral, " +
          "PublicKeyToken=0738eb9f132ed756");

        Type syscall = replacedembly.GetType("Mono.Unix.Native.Syscall");
        MethodInfo mmap = syscall.GetMethod("mmap");

        Type mmapProts = replacedembly.GetType("Mono.Unix.Native.MmapProts");
        object mmapProtsParam = Enum.ToObject(mmapProts,
          (int)mmapProts.GetField("PROT_READ").GetValue(null) |
          (int)mmapProts.GetField("PROT_WRITE").GetValue(null) |
          (int)mmapProts.GetField("PROT_EXEC").GetValue(null));

        Type mmapFlags = replacedembly.GetType("Mono.Unix.Native.MmapFlags");
        object mmapFlagsParam = Enum.ToObject(mmapFlags,
          (int)mmapFlags.GetField("MAP_ANONYMOUS").GetValue(null) |
          (int)mmapFlags.GetField("MAP_PRIVATE").GetValue(null));
        
        codeBuffer = (IntPtr)mmap.Invoke(null, new object[] { IntPtr.Zero, 
          size, mmapProtsParam, mmapFlagsParam, -1, 0 });        
      } else { // Windows
        codeBuffer = NativeMethods.VirtualAlloc(IntPtr.Zero,
          (UIntPtr)size, AllocationType.COMMIT | AllocationType.RESERVE, 
          MemoryProtection.EXECUTE_READWRITE);
      }

      Marshal.Copy(rdtscCode, 0, codeBuffer, rdtscCode.Length);

      Rdtsc = Marshal.GetDelegateForFunctionPointer(
        codeBuffer, typeof(RdtscDelegate)) as RdtscDelegate;

      IntPtr cpuidAddress = (IntPtr)((long)codeBuffer + rdtscCode.Length);
      Marshal.Copy(cpuidCode, 0, cpuidAddress, cpuidCode.Length);

      Cpuid = Marshal.GetDelegateForFunctionPointer(
        cpuidAddress, typeof(CpuidDelegate)) as CpuidDelegate;         
    }

19 View Source File : EnumExtension.cs
License : MIT License
Project Creator : AlphaYu

public static string GetDescription([NotNull] this Enum value)
        {
            var attr = value.GetType().GetField(value.ToString())
                .GetCustomAttribute<DescriptionAttribute>();
            return attr?.Description;
        }

19 View Source File : CommonExtend.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string GetEnumValDesc(this Enum enumObj, object val)
        {
            var enumType = enumObj.GetType();
            var text = enumType.GetEnumName(val);
            var descText = enumType.GetField(text).GetCustomAttributes(typeof(DescriptionAttribute),
                    false).Cast<DescriptionAttribute>().FirstOrDefault()?.Description;
            text = string.IsNullOrWhiteSpace(descText) ? text : descText;

            return text;
        }

19 View Source File : DefineSetter.cs
License : MIT License
Project Creator : alelievr

static bool IsObsolete(BuildTargetGroup group)
        {
            var attrs = typeof(BuildTargetGroup)
                .GetField(group.ToString())
                .GetCustomAttributes(typeof(ObsoleteAttribute), false);

            return attrs != null && attrs.Length > 0;
        }

19 View Source File : SteamVR_ExternalCamera.cs
License : MIT License
Project Creator : ajayyy

public void ReadConfig()
	{
		try
		{
			var mCam = new HmdMatrix34_t();
			var readCamMatrix = false;

			object c = config; // box
			var lines = System.IO.File.ReadAllLines(configPath);
			foreach (var line in lines)
			{
				var split = line.Split('=');
				if (split.Length == 2)
				{
					var key = split[0];
					if (key == "m")
					{
						var values = split[1].Split(',');
						if (values.Length == 12)
						{
							mCam.m0 = float.Parse(values[0]);
							mCam.m1 = float.Parse(values[1]);
							mCam.m2 = float.Parse(values[2]);
							mCam.m3 = float.Parse(values[3]);
							mCam.m4 = float.Parse(values[4]);
							mCam.m5 = float.Parse(values[5]);
							mCam.m6 = float.Parse(values[6]);
							mCam.m7 = float.Parse(values[7]);
							mCam.m8 = float.Parse(values[8]);
							mCam.m9 = float.Parse(values[9]);
							mCam.m10 = float.Parse(values[10]);
							mCam.m11 = float.Parse(values[11]);
							readCamMatrix = true;
						}
					}
#if !UNITY_METRO
					else if (key == "disableStandardreplacedets")
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, bool.Parse(split[1]));
					}
					else
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, float.Parse(split[1]));
					}
#endif
				}
			}
			config = (Config)c; //unbox

			// Convert calibrated camera matrix settings.
			if (readCamMatrix)
			{
				var t = new SteamVR_Utils.RigidTransform(mCam);
				config.x = t.pos.x;
				config.y = t.pos.y;
				config.z = t.pos.z;
				var angles = t.rot.eulerAngles;
				config.rx = angles.x;
				config.ry = angles.y;
				config.rz = angles.z;
			}
		}
		catch { }

		// Clear target so AttachToCamera gets called to pick up any changes.
		target = null;
#if !UNITY_METRO
		// Listen for changes.
		if (watcher == null)
		{
			var fi = new System.IO.FileInfo(configPath);
			watcher = new System.IO.FileSystemWatcher(fi.DirectoryName, fi.Name);
			watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
			watcher.Changed += new System.IO.FileSystemEventHandler(OnChanged);
			watcher.EnableRaisingEvents = true;
		}
	}

19 View Source File : TypeHelpers.cs
License : MIT License
Project Creator : adrianoc

public static FieldInfo ResolveField(string declaringType, string fieldName)
        {
            var type = Type.GetType(declaringType);
            if (type == null)
            {
                throw new Exception("Could not resolve field: '" + fieldName + "'. Type '" + declaringType + "' not found.");
            }

            return type.GetField(fieldName);
        }

19 View Source File : AttachStrategyEditor.cs
License : MIT License
Project Creator : all-iver

void DoChangeTransitionerButton() {
            if (GUILayout.Button("Change Transitioner")) {
                System.Type[] transitionerTypes = System.AppDomain.CurrentDomain.GetAllDerivedTypes(
                        typeof(Transitioner));
    			GenericMenu genericMenu = new GenericMenu();
                genericMenu.AddItem(new GUIContent("None"), false, new GenericMenu.MenuFunction(() => {
                    SetTransitioner(selectedCategoryProp.intValue, null);
                }));
                foreach (System.Type t in transitionerTypes) {
                    MethodInfo methodInfo = t.GetMethod("SupportsAttachStrategyType",
                            BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public);
                    if (methodInfo != null)
                        if (!(bool) methodInfo.Invoke(null, new object[] { serializedObject.targetObject.GetType() }))
                            continue;

                    string displayName = t.FullName;
                    if (t.GetField("displayName") != null)
                        displayName = (string) t.GetField("displayName").GetValue(null);
                    genericMenu.AddItem(new GUIContent(displayName), false, new GenericMenu.MenuFunction(() => {
                        SetTransitioner(selectedCategoryProp.intValue, t);
                    }));
                }
                genericMenu.ShowAsContext();
            }
        }

19 View Source File : EnumType.cs
License : Apache License 2.0
Project Creator : 91270

public static string GetEnumText(this Enum obj)
        {
            Type type = obj.GetType();
            FieldInfo field = type.GetField(obj.ToString());
            TextAttribute attribute = (TextAttribute)field.GetCustomAttribute(typeof(TextAttribute));
            return attribute.Value;
        }

19 View Source File : Enums.cs
License : MIT License
Project Creator : Analogy-LogViewer

public static string GetDisplay(this Enum value)

        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            DisplayAttribute[] attributes = (DisplayAttribute[])value.GetType().GetField(value.ToString())
                .GetCustomAttributes(typeof(DisplayAttribute), false);
            if (attributes.Count() != 1)
            {
                throw new ArgumentOutOfRangeException();
            }

            return attributes[0].Name;

        }

19 View Source File : PrefixWriter.cs
License : MIT License
Project Creator : Abc-Arbitrage

private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollection<PatternPart> parts, Dictionary<string, (int offset, int length)> stringMap)
        {
            var method = new DynamicMethod("WritePrefix", typeof(void), new[] { typeof(PrefixWriter), typeof(ILogEventHeader) }, typeof(PrefixWriter), false)
            {
                InitLocals = false
            };

            var il = method.GetILGenerator();

            var stringBufferLocal = il.DeclareLocal(typeof(StringBuffer));
            var stringsLocal = il.DeclareLocal(typeof(char).MakeByRefType(), true);
            var dateTimeLocal = default(LocalBuilder);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_stringBuffer), BindingFlags.Instance | BindingFlags.NonPublic)!);
            il.Emit(OpCodes.Stloc, stringBufferLocal);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_strings), BindingFlags.Instance | BindingFlags.NonPublic)!);
            il.Emit(OpCodes.Ldc_I4_0);
            il.Emit(OpCodes.Ldelema, typeof(char));
            il.Emit(OpCodes.Stloc, stringsLocal);

            foreach (var part in parts)
            {
                switch (part.Type)
                {
                    case PatternPartType.String:
                    {
                        // _stringBuffer.Append(&_strings[0] + offset * sizeof(char), length);

                        var (offset, length) = stringMap[part.Value!];

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldloc, stringsLocal);
                        il.Emit(OpCodes.Conv_U);
                        il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
                        il.Emit(OpCodes.Add);

                        il.Emit(OpCodes.Ldc_I4, length);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(char*), typeof(int) })!);
                        break;
                    }

                    case PatternPartType.Date:
                    {
                        // _stringBuffer.Append(logEventHeader.Timestamp, new StringView(&_strings[0] + offset * sizeof(char), length));

                        var (offset, length) = stringMap[_dateFormat];

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);

                        il.Emit(OpCodes.Ldloc, stringsLocal);
                        il.Emit(OpCodes.Conv_U);
                        il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
                        il.Emit(OpCodes.Add);

                        il.Emit(OpCodes.Ldc_I4, length);

                        il.Emit(OpCodes.Newobj, typeof(StringView).GetConstructor(new[] { typeof(char*), typeof(int) })!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(DateTime), typeof(StringView) })!);
                        break;
                    }

                    case PatternPartType.Time:
                    {
                        // _stringBuffer.Append(logEventHeader.Timestamp.TimeOfDay, StringView.Empty);

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);
                        il.Emit(OpCodes.Stloc, dateTimeLocal ??= il.DeclareLocal(typeof(DateTime)));
                        il.Emit(OpCodes.Ldloca, dateTimeLocal);
                        il.Emit(OpCodes.Call, typeof(DateTime).GetProperty(nameof(DateTime.TimeOfDay))?.GetGetMethod()!);

                        il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty))!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(TimeSpan), typeof(StringView) })!);
                        break;
                    }

                    case PatternPartType.Thread:
                    {
                        // AppendThread(logEventHeader.Thread);

                        il.Emit(OpCodes.Ldarg_0);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Thread))?.GetGetMethod()!);

                        il.Emit(OpCodes.Call, typeof(PrefixWriter).GetMethod(nameof(AppendThread), BindingFlags.Instance | BindingFlags.NonPublic)!);
                        break;
                    }

                    case PatternPartType.Level:
                    {
                        // _stringBuffer.Append(LevelStringCache.GetLevelString(logEventHeader.Level));

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Level))?.GetGetMethod()!);
                        il.Emit(OpCodes.Call, typeof(LevelStringCache).GetMethod(nameof(LevelStringCache.GetLevelString))!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
                        break;
                    }

                    case PatternPartType.Logger:
                    {
                        // _stringBuffer.Append(logEventHeader.Name);

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Name))?.GetGetMethod()!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
                        break;
                    }

                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            il.Emit(OpCodes.Ret);

            return (Action<PrefixWriter, ILogEventHeader>)method.CreateDelegate(typeof(Action<PrefixWriter, ILogEventHeader>));
        }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : albyho

private static string GetEnumDisplayName(this object enumValue, Type type)
        {
            var enumName = Enum.GetName(type, enumValue);
            if (enumName == null) return null;

            var attributes = type.GetField(enumName).GetCustomAttributes(typeof(DisplayAttribute), false);
            if (attributes.Length > 0)
                return ((DisplayAttribute)attributes[0]).GetName(); // TODO: (alby)如果 DisplayAttribute 的 DisplayName 属性为 IsNullOrWhiteSpace ,尝试从资源文件获取
            else
                return enumValue.ToString();
        }

19 View Source File : EnumConverter.cs
License : MIT License
Project Creator : AkiniKites

public static string GetEnumDescription(Enum value)
        {
            var fi = value.GetType().GetField(value.ToString());

            if (fi.GetCustomAttributes(typeof(DescriptionAttribute), false) is DescriptionAttribute[] attributes && attributes.Any())
                return attributes.First().Description;

            return value.ToString();
        }

19 View Source File : ConnectionData.cs
License : MIT License
Project Creator : Adoxio

public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			if (!destinationType.Equals(typeof(string)))
			{
				throw new ArgumentException(@"Can only convert to string.", "destinationType");
			}

			var name = value.ToString();

			var attrs = value.GetType().GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);

			return (attrs.Length > 0) ? ((DescriptionAttribute)attrs[0]).Description : name;
		}

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : AlexanderPro

internal static TAttribute GetSingleAttributeOrNull<TAttribute>(this Enum value) where TAttribute : Attribute
        {
            var attribute = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(TAttribute), false).SingleOrDefault() as TAttribute;
            return attribute;
        }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : 52ABP

public static void Each(this Type enumType, Action<string, string, string> action)
        {
            if (enumType.BaseType != typeof (Enum))
            {
                return;
            }
            var arr = Enum.GetValues(enumType);
            foreach (var name in arr)
            {
                var value = (int) Enum.Parse(enumType, name.ToString());
                var fieldInfo = enumType.GetField(name.ToString());
                var description = "";
                if (fieldInfo != null)
                {
                    var attr = Attribute.GetCustomAttribute(fieldInfo,
                        typeof (DescriptionAttribute), false) as DescriptionAttribute;
                    if (attr != null)
                    {
                        description = attr.Description;
                    }
                }
                action(name.ToString(), value.ToString(), description);
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : alexmg

private static string GetVersion() =>
            (string)typeof(Program).replacedembly
                .GetType(nameof(GitVersionInformation))
                .GetField(nameof(GitVersionInformation.LegacySemVer))
                .GetValue(null);

19 View Source File : ReflectionExtend.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string GetFieldDescription(this Type type, string field)
        {
            return type.GetField(field).GetDescription();
        }

19 View Source File : MidiState.cs
License : MIT License
Project Creator : allenwp

public void replacedignControl(object controlledObject, string fieldPropertyName, byte replacedignmentButton)
        {
            var propertyInfo = controlledObject.GetType().GetProperty(fieldPropertyName);
            if (propertyInfo != null)
            {
                replacedignControl(controlledObject, new FieldPropertyListInfo(propertyInfo, controlledObject), replacedignmentButton);
            }
            else
            {
                var fieldInfo = controlledObject.GetType().GetField(fieldPropertyName);
                if (fieldInfo != null)
                {
                    replacedignControl(controlledObject, new FieldPropertyListInfo(fieldInfo, controlledObject), replacedignmentButton);
                }
                else
                {
                    throw new Exception("Failed to replacedign control of property or field with name " + fieldPropertyName);
                }
            }
        }

19 View Source File : EmitHelper.cs
License : MIT License
Project Creator : 1996v

public static void EmitDefault(this ILGenerator il, Type type)
        {
            switch (Type.GetTypeCode(type))
            {
                case TypeCode.DateTime:
                    il.Emit(OpCodes.Ldsfld, typeof(DateTime).GetField(nameof(DateTime.MinValue)));
                    return;
                case TypeCode.Decimal:
                    il.Emit(OpCodes.Ldsfld, typeof(decimal).GetField(nameof(decimal.Zero)));
                    return;
                case TypeCode.Boolean:
                case TypeCode.Char:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.Int16:
                case TypeCode.UInt16:
                case TypeCode.Int32:
                case TypeCode.UInt32:
                    il.Emit(OpCodes.Ldc_I4_0);
                    return;

                case TypeCode.Int64:
                case TypeCode.UInt64:
                    il.Emit(OpCodes.Ldc_I4_0);
                    il.Emit(OpCodes.Conv_I8);
                    return;

                case TypeCode.Single:
                    il.Emit(OpCodes.Ldc_R4, default(float));
                    return;

                case TypeCode.Double:
                    il.Emit(OpCodes.Ldc_R8, default(double));
                    return;
            }

            if (type.IsValueType)
            {
                LocalBuilder lb = il.DeclareLocal(type);
                il.Emit(OpCodes.Ldloca, lb);
                il.Emit(OpCodes.Initobj, type);
                il.Emit(OpCodes.Ldloc, lb);
            }
            else
            {
                il.Emit(OpCodes.Ldnull);
            }
        }

19 View Source File : EnumToIconKeyConverter.cs
License : MIT License
Project Creator : ambleside138

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return "";

            var fi = value.GetType().GetField(value.ToString());
            if (fi == null)
                return "";

            var attribute = (IconKeyAttribute)Attribute.GetCustomAttribute(fi, typeof(IconKeyAttribute));

            return attribute.Key;
        }

19 View Source File : Enumerations.cs
License : MIT License
Project Creator : ahmed-abdelrazek

public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes != null && attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            else
            {
                return value.ToString();
            }
        }

19 View Source File : EnumControl.cs
License : MIT License
Project Creator : ahydrax

private static string GetDescription(Type enumType, string valueName)
            => enumType.GetField(valueName)
                ?.GetCustomAttribute<DescriptionAttribute>()
                ?.Description;

19 View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo Build(DynamicFormatterreplacedembly replacedembly, ObjectSerializationInfo serializationInfo)
        {
            Type type = serializationInfo.Type;
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
            serializationInfo.SerializeMemberInfosOrderByKeyIndex(type);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);

            Type delegateCacheType = typeof(Array3DelegateCache<>).MakeGenericType(type);
            delegateCacheType.GetMethod(nameof(Array3DelegateCache<int>.Factory), BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { replacedembly, serializationInfo });

            TypeBuildHelper.CallSerializeDelegate(serializeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Serialize)));
            TypeBuildHelper.CallSizeDelegate(sizeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Size)));
            TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Deserialize)));

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : DefaultContractResolver.cs
License : MIT License
Project Creator : akaskela

private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess)
        {
            MemberInfo specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix);
            if (specifiedMember == null)
            {
                specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix);
            }

            if (specifiedMember == null || ReflectionUtils.GetMemberUnderlyingType(specifiedMember) != typeof(bool))
            {
                return;
            }

            Func<object, object> specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(specifiedMember);

            property.GetIsSpecified = o => (bool)specifiedPropertyGet(o);

            if (ReflectionUtils.CanSetMemberValue(specifiedMember, allowNonPublicAccess, false))
            {
                property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet<object>(specifiedMember);
            }
        }

19 View Source File : OVRSystemProfilerPanel.cs
License : MIT License
Project Creator : absurd-joy

void GetMetricsField(string propertyName, out FieldInfo baseFieldInfo, out FieldInfo validalityFieldInfo)
	{
		baseFieldInfo = typeof(OVRSystemPerfMetrics.PerfMetrics).GetField(propertyName);
		validalityFieldInfo = typeof(OVRSystemPerfMetrics.PerfMetrics).GetField(propertyName + "_IsValid");
	}

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : albyho

private static string GetEnumRawConstantValue(this object enumValue, Type type)
        {
            var filedInfo = type.GetField(Enum.GetName(type, enumValue));
            return filedInfo.GetRawConstantValue().ToString();
        }

19 View Source File : AudioKernelExtensions.cs
License : MIT License
Project Creator : aksyr

static SampleProviderDescriptionData CreateSampleProviderDescription()
            {
                var pType = typeof(TProviders);
                if (!pType.IsEnum)
                    throw new ArgumentException("CreateDSPNode<Parameters, Providers, T> must have Providers as an enum.");

                var pValues = Enum.GetValues(pType);
                for (var i = 0; i < pValues.Length; i++)
                {
                    if ((int)pValues.GetValue(i) != i)
                        throw new ArgumentException("CreateDSPNode<Parameters, Providers, T> enum values must start at 0 and be consecutive");
                }

                var provsDescriptions = Utility.AllocateUnsafe<DSPSampleProviderDescription>(pValues.Length, Allocator.Persistent, true);
                for (var i = 0; i < pValues.Length; i++)
                {
                    provsDescriptions[i].m_IsArray = false;
                    provsDescriptions[i].m_Size = -1;

                    var field = pType.GetField(Enum.GetName(pType, pValues.GetValue(i)));

                    var arrayAttr = (SampleProviderArrayAttribute)Attribute.GetCustomAttribute(field, typeof(SampleProviderArrayAttribute));
                    if (arrayAttr != null)
                    {
                        provsDescriptions[i].m_IsArray = true;
                        provsDescriptions[i].m_Size = arrayAttr.Size;
                    }
                }

                return new SampleProviderDescriptionData
                {
                    Descriptions = provsDescriptions,
                    SampleProviderCount = pValues.Length
                };
            }

19 View Source File : EmbeddedIconProvider.android.cs
License : MIT License
Project Creator : adenearnshaw

public async Task<object> CreatePlatformIcon(IShortcutIcon shortcutIcon)
        {
            var iconTypeString = shortcutIcon.IconName.ToLower();
            var iconName = $"ic_plugin_sc_{iconTypeString}";
            var resourceId = (int)(typeof(Plugin.AppShortcuts.Resource.Drawable).GetField(iconName)?.GetValue(null) ?? 0);
            var icon = Icon.CreateWithResource(Application.Context, resourceId);
            return icon;
        }

19 View Source File : GraphCLI.Executer.cs
License : MIT License
Project Creator : alelievr

static void	CreateNode(BaseGraph graph, BaseGraphCommand command, string inputCommand)
		{
			Vector2	position = command.position;
			BaseNode node = null;
			
			//if we receive a CreateNode with input/output graph nodes, we replacedign them so we don't have multiple inout/output nodes
			if (NodeTypeProvider.inputGraphTypes.Contains(command.nodeType))
				node = graph.inputNode;
			else if (NodeTypeProvider.outputGraphTypes.Contains(command.nodeType))
				node = graph.outputNode;
			else
				node = graph.CreateNewNode(command.nodeType, position);
			
			//set the position again for input/output nodes
			node.rect.position = position;
			
			Type nodeType = node.GetType();

			if (!String.IsNullOrEmpty(command.attributes))
			{
				foreach (var attr in Jsonizer.Parse(command.attributes))
				{
					FieldInfo attrField = nodeType.GetField(attr.first, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

					if (attrField != null)
						attrField.SetValue(node, attr.second);
					else
						Debug.LogError("Attribute " + attr.first + " can be found in node " + node);
				}
			}

			node.name = command.name;
		}

19 View Source File : JsonExtension.cs
License : MIT License
Project Creator : 4egod

public static T ToEnum<T>(this string str)
        {
            var enumType = typeof(T);
            foreach (var name in Enum.GetNames(enumType))
            {
                var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
                if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
            }
            //throw exception or whatever handling you want or
            return default(T);
        }

19 View Source File : EditorHelper.cs
License : MIT License
Project Creator : alen-smajic

public static void SetTargetObjectOfProperty(SerializedProperty prop, object value)
		{
			var path = prop.propertyPath.Replace(".Array.data[", "[");
			object obj = prop.serializedObject.targetObject;
			var elements = path.Split('.');
			foreach (var element in elements.Take(elements.Length - 1))
			{
				if (element.Contains("["))
				{
					var elementName = element.Substring(0, element.IndexOf("[", StringComparison.CurrentCulture));
					var index = System.Convert.ToInt32(element.Substring(element.IndexOf("[", StringComparison.CurrentCulture)).Replace("[", "").Replace("]", ""));
					obj = GetValue_Imp(obj, elementName, index);
				}
				else
				{
					obj = GetValue_Imp(obj, element);
				}
			}

			if (System.Object.ReferenceEquals(obj, null)) return;

			try
			{
				var element = elements.Last();

				if (element.Contains("["))
				{
					var tp = obj.GetType();
					var elementName = element.Substring(0, element.IndexOf("[", StringComparison.CurrentCulture));
					var index = System.Convert.ToInt32(element.Substring(element.IndexOf("[", StringComparison.CurrentCulture)).Replace("[", "").Replace("]", ""));
					var field = tp.GetField(elementName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
					var arr = field.GetValue(obj) as System.Collections.IList;
					arr[index] = value;
				}
				else
				{
					var tp = obj.GetType();
					var field = tp.GetField(element, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
					if (field != null)
					{
						field.SetValue(obj, value);
					}
				}

			}
			catch
			{
				return;
			}
		}

19 View Source File : SettingsModel.cs
License : MIT License
Project Creator : adrianmteo

private static IEnumerable<KeyValuePair<T, string>> GetKeyValuePairFromEnum<T>()
        {
            Type type = typeof(T);

            IEnumerable<T> values = Enum.GetValues(type).Cast<T>();

            return values.Select((value) =>
            {
                DescriptionAttribute[] attributes = (DescriptionAttribute[])type.GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);

                string description = "";

                if (attributes.Length > 0)
                {
                    description = attributes.First().Description;
                }

                return new KeyValuePair<T, string>(value, description);
            });
        }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : AlexanderPro

public static string GetDescription(this Enum value)
        {
            var attribute = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
            var description = attribute == null ? null : attribute.Description;
            return description;
        }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : 17MKH

public static string ToDescription(this Enum value)
    {
        var type = value.GetType();
        var info = type.GetField(value.ToString());
        var key = type.FullName + info.Name;
        if (!DescriptionCache.TryGetValue(key, out string desc))
        {
            var attrs = info.GetCustomAttributes(typeof(DescriptionAttribute), true);
            if (attrs.Length < 1)
                desc = string.Empty;
            else
                desc = attrs[0] is DescriptionAttribute
                    descriptionAttribute
                    ? descriptionAttribute.Description
                    : value.ToString();

            DescriptionCache.TryAdd(key, desc);
        }

        return desc;
    }

19 View Source File : NodeComboBox.cs
License : MIT License
Project Creator : AlexGyver

private Control CreateCheckedListBox(TreeNodeAdv node)
		{
			CheckedListBox listBox = new CheckedListBox();
			listBox.CheckOnClick = true;

			object value = GetValue(node);
			Type enumType = GetEnumType(node);
			foreach (object obj in Enum.GetValues(enumType))
			{
				object[] attributes = enumType.GetField(obj.ToString()).GetCustomAttributes(typeof(BrowsableAttribute), false);
				if (attributes.Length == 0 || ((BrowsableAttribute)attributes[0]).Browsable)
					listBox.Items.Add(obj, IsContain(value, obj));
			}

			SetEditControlProperties(listBox, node);
			if (CreatingEditor != null)
				CreatingEditor(this, new EditEventArgs(node, listBox));
			return listBox;
		}

19 View Source File : SwimPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static IEnumerable<CodeInstruction> Farmer_updateCommon_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            try
            {
                bool startLooking = false;
                int start = -1;
                int end = -1;
                for (int i = 0; i < codes.Count; i++)
                {
                    if (startLooking)
                    {
                        if(start == -1 && codes[i].opcode == OpCodes.Ldfld && codes[i].operand as FieldInfo == typeof(Farmer).GetField("timerSinceLastMovement"))
                        {
                            start = i - 1;
                            Monitor.Log($"start at {start}");
                        }
                        if (codes[i].opcode == OpCodes.Stfld && codes[i].operand as FieldInfo == typeof(Farmer).GetField("health"))
                        {
                            end = i + 1;
                            Monitor.Log($"end at {end}");
                        }
                    }
                    else if (codes[i].operand as string == "slosh")
                    {
                        startLooking = true;
                    }
                }
                if(start > -1 && end > start)
                {
                    codes.RemoveRange(start, end - start);
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(Farmer_updateCommon_Transpiler)}:\n{ex}", LogLevel.Error);
            }

            return codes.AsEnumerable();
        }

19 View Source File : OpenEdgeParameterExtractingExpressionVisitor.cs
License : Apache License 2.0
Project Creator : alexwiese

protected Expression VisitNewMember(MemberExpression memberExpression)
        {
            if (memberExpression.Expression is ConstantExpression constant
                && constant.Value != null)
            {
                switch (memberExpression.Member.MemberType)
                {
                    case MemberTypes.Field:
                        return Expression.Constant(constant.Value.GetType().GetField(memberExpression.Member.Name).GetValue(constant.Value));

                    case MemberTypes.Property:
                        var propertyInfo = constant.Value.GetType().GetProperty(memberExpression.Member.Name);
                        if (propertyInfo == null)
                        {
                            break;
                        }

                        return Expression.Constant(propertyInfo.GetValue(constant.Value));
                }
            }

            return base.VisitMember(memberExpression);
        }

19 View Source File : NotchSolutionDebugger.cs
License : MIT License
Project Creator : 5argon

public void Export()
    {
        device = new SimulationDevice();

        device.Meta = new MetaData();
        device.Meta.friendlyName = export.GetComponentInChildren<InputField>().text;

        device.SystemInfo = new SystemInfoData() { GraphicsDependentData = new GraphicsDependentSystemInfoData[1] { new GraphicsDependentSystemInfoData() } };
        foreach (var property in typeof(SystemInfo).GetProperties(BindingFlags.Public | BindingFlags.Static))
        {
            var prop = typeof(SystemInfoData).GetField(property.Name);
            if (prop != null) prop.SetValue(device.SystemInfo, property.GetValue(null));
            else
            {
                prop = typeof(GraphicsDependentSystemInfoData).GetField(property.Name);
                if (prop != null) prop.SetValue(device.SystemInfo.GraphicsDependentData[0], property.GetValue(null));
            }
        }

        device.Screens = new ScreenData[1];
        for (int i = 0; i < device.Screens.Length; i++)
        {
            var screen = new ScreenData();
            screen.width = Screen.width;
            screen.height = Screen.height;
            //screen.navigationBarHeight = 0;
            screen.orientations = new Dictionary<ScreenOrientation, OrientationDependentData>();
            screen.dpi = Screen.dpi;
            device.Screens[i] = screen;
            StartCoroutine(screenData(screen));
        }

        menu = Menu.Extracting;
    }

19 View Source File : BuiltinResolver.cs
License : Apache License 2.0
Project Creator : allenai

internal static object GetFormatter(Type t)
        {
            object formatter;
            if (FormatterMap.TryGetValue(t, out formatter))
            {
                return formatter;
            }

            if (typeof(Type).IsreplacedignableFrom(t))
            {
                return typeof(TypeFormatter<>).MakeGenericType(t).GetField(nameof(TypeFormatter<Type>.Instance)).GetValue(null);
            }

            return null;
        }

19 View Source File : CommonExtend.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Dictionary<int, string> GetEnumValAndDescList(this Enum enumObj)
        {
            var enumDic = new Dictionary<int, string>();
            var enumType = enumObj.GetType();
            var enumValues = enumType.GetEnumValues().Cast<int>().ToList();

            enumValues.ForEach(item =>
            {
                var key = (int)item;
                var text = enumType.GetEnumName(key);
                var descText = enumType.GetField(text).GetCustomAttributes(typeof(DescriptionAttribute),
                    false).Cast<DescriptionAttribute>().FirstOrDefault()?.Description;

                text = string.IsNullOrWhiteSpace(descText) ? text : descText;

                enumDic.Add(key, text);
            });

            return enumDic;
        }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : alonsoalon

public static string ToDescription(this Enum item)
        {
            string name = item.ToString();
            var desc = item.GetType().GetField(name)?.GetCustomAttribute<DescriptionAttribute>();
            return desc?.Description ?? name;
        }

19 View Source File : XnaToFnaUtil.Processor.cs
License : zlib License
Project Creator : 0x0ade

public OpCode ShortToLongOp(OpCode op) {
            string name = Enum.GetName(typeof(Code), op.Code);
            if (!name.EndsWith("_S"))
                return op;
            return (OpCode?) typeof(OpCodes).GetField(name.Substring(0, name.Length - 2))?.GetValue(null) ?? op;
        }

19 View Source File : EnumToDisplayTextConverter.cs
License : MIT License
Project Creator : ambleside138

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return "";

            var fi = value.GetType().GetField(value.ToString());
            if (fi == null)
                return "";

            var attribute = (DisplayTextAttribute)Attribute.GetCustomAttribute(fi, typeof(DisplayTextAttribute));

            return attribute.Text;
        }

19 View Source File : ZSymbol.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static void PickupConstantSymbols<T>(ref IDictionary<ZSymbol, string> symbols)
            where T : ZSymbol
		{
			Type type = typeof(T);

			FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);

			Type codeType = type.GetNestedType("Code", BindingFlags.NonPublic);

			// Pickup constant symbols
			foreach (FieldInfo symbolField in fields.Where(f => typeof(ZSymbol).IsreplacedignableFrom(f.FieldType)))
			{
				FieldInfo symbolCodeField = codeType.GetField(symbolField.Name);
				if (symbolCodeField != null)
				{
					int symbolNumber = (int)symbolCodeField.GetValue(null);

				    var symbol = Activator.CreateInstance(
				        type,
				        BindingFlags.NonPublic | BindingFlags.Instance, 
				        null,
				        new object[] {symbolNumber},
				        null);
					symbolField.SetValue(null, symbol);
					symbols.Add((ZSymbol)symbol, symbolCodeField.Name);
				}
			}
		}

19 View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin

private static void SetAvatarDestroyParent(UMADynamicAvatar avatar, bool destroyParent)
		{
			var umaEditorAvatarType = GetUMAEditorAvatarType();
			var umaEditorAvatar = avatar.GetComponentInChildren(umaEditorAvatarType);
			umaEditorAvatarType.GetField("destroyParent").SetValue(umaEditorAvatar, destroyParent);
		}

19 View Source File : XnaToFnaHelper.cs
License : zlib License
Project Creator : 0x0ade

public static void PlatformHook(string name) {
            Type t_Helper = typeof(XnaToFnaHelper);

            replacedembly fna = replacedembly.Getreplacedembly(typeof(Game));
            FieldInfo field = fna.GetType("Microsoft.Xna.Framework.FNAPlatform").GetField(name);

            // Store the original delegate into fna_name.
            t_Helper.GetField($"fna_{name}").SetValue(null, field.GetValue(null));
            // Replace the value with the new method.
            field.SetValue(null, Delegate.CreateDelegate(fna.GetType($"Microsoft.Xna.Framework.FNAPlatform+{name}Func"), t_Helper.GetMethod(name)));
        }

19 View Source File : XnaToFnaUtil.Processor.cs
License : zlib License
Project Creator : 0x0ade

public OpCode LongToShortOp(OpCode op) {
            string name = Enum.GetName(typeof(Code), op.Code);
            if (name.EndsWith("_S"))
                return op;
            return (OpCode?) typeof(OpCodes).GetField(name + "_S")?.GetValue(null) ?? op;
        }

19 View Source File : JsonExtension.cs
License : MIT License
Project Creator : 4egod

public static string ToEnumString<T>(this T type)
        {
            var enumType = typeof (T);
            var name = Enum.GetName(enumType, type);
            var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
            return enumMemberAttribute.Value;
        }

19 View Source File : EnumDescriptionTypeConverter.cs
License : MIT License
Project Creator : Actipro

public static String GetDescription(Type type, string fieldName) {
			if (null != type && null != fieldName) {
				FieldInfo fieldInfo = type.GetField(fieldName);
				if (null != fieldInfo) {
					DescriptionAttribute[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
					if (null != attributes && 0 != attributes.Length)
						return attributes[0].Description;
				}

				return fieldName;
			}

			return string.Empty;
		}

19 View Source File : AudioKernelExtensions.cs
License : MIT License
Project Creator : aksyr

static ParameterDescriptionData CreateParameterDescription()
            {
                var pType = typeof(TParameters);
                if (!pType.IsEnum)
                    throw new ArgumentException("CreateDSPNode<Parameters, Providers, T> must have Parameters as an enum.");

                var pValues = Enum.GetValues(pType);
                for (var i = 0; i < pValues.Length; i++)
                {
                    if ((int)pValues.GetValue(i) != i)
                        throw new ArgumentException("CreateDSPNode<Parameters, Providers, T> enum values must start at 0 and be consecutive");
                }

                var paramsDescriptions = Utility.AllocateUnsafe<DSPParameterDescription>(pValues.Length, Allocator.Persistent, true);
                for (var i = 0; i < pValues.Length; i++)
                {
                    paramsDescriptions[i].Min = float.MinValue;
                    paramsDescriptions[i].Max = float.MaxValue;
                    paramsDescriptions[i].DefaultValue = 0.0f;
                    var field = pType.GetField(Enum.GetName(pType, pValues.GetValue(i)));

                    var rangeAttr = (ParameterRangeAttribute)Attribute.GetCustomAttribute(field, typeof(ParameterRangeAttribute));
                    if (rangeAttr != null)
                    {
                        paramsDescriptions[i].Min = rangeAttr.Min;
                        paramsDescriptions[i].Max = rangeAttr.Max;
                    }

                    var defValAttr = (ParameterDefaultAttribute)Attribute.GetCustomAttribute(field, typeof(ParameterDefaultAttribute));
                    if (defValAttr != null)
                    {
                        paramsDescriptions[i].DefaultValue = defValAttr.DefaultValue;
                    }
                }

                var data = new ParameterDescriptionData
                {
                    Descriptions = paramsDescriptions,
                    ParameterCount = pValues.Length
                };

                return data;
            }

See More Examples