CSharp examples for System.Reflection:Modifier
Is Constant
using System.Threading.Tasks; using System.Text; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Reflection.Emit; using System.Reflection; using System.Linq; using System.IO;/*from www .j a v a 2s . c o m*/ using System.Globalization; using System.Collections.Generic; using System; public class Main{ public static bool IsConstant(this PropertyInfo prop) { var getMtd = prop.GetMethod; // virtual methods can't be proven constant, who knows what overrides are out there if (getMtd == null || getMtd.IsVirtual) return false; var instrs = Utils.Decompile(getMtd); if (instrs == null) return false; // anything control flow-y, call-y, load-y, etc. means the property isn't constant var hasNonConstantInstructions = instrs.Any(a => !ReadOnlyOpCodes.Contains(a.Item1) && a.Item1 != OpCodes.Ret); if (hasNonConstantInstructions) return false; // if *two* constants are in play (somehow) we can't tell which one to propagate so break it var numberOfConstants = instrs.Count(a => ConstantLoadOpCodes.Contains(a.Item1) || a.Item2.HasValue || a.Item3.HasValue || a.Item4.HasValue); if (numberOfConstants != 1) return false; return true; } public static bool IsConstant(this FieldInfo field) { try { return field.IsLiteral && field.ReturnType().IsPropagatableType() && field.GetRawConstantValue() != null; } catch (Exception) { // Something went sideways, bail return false; } } public static bool IsConstant(this MemberInfo member) { var asField = member as FieldInfo; if (asField != null) return asField.IsConstant(); var asProp = member as PropertyInfo; if (asProp != null) return asProp.IsConstant(); throw new Exception("Expected member to be a FieldInfo or PropertyInfo, found: " + member); } public static bool IsPropagatableType(this Type t) { return t == typeof(string) || t == typeof(char) || t == typeof(float) || t == typeof(double) || t == typeof(byte) || t == typeof(sbyte) || t == typeof(short) || t == typeof(ushort) || t == typeof(int) || t == typeof(uint) || t == typeof(long) || t == typeof(ulong) || t == typeof(bool) || t.IsEnum(); } public static Type ReturnType(this MemberInfo m) { var asField = m as FieldInfo; var asProp = m as PropertyInfo; return asField != null ? asField.FieldType : asProp.PropertyType; } public static MethodInfo GetMethod(this Type type, string name, BindingFlags flags, Type[] parameterTypes) { var info = type.GetTypeInfo(); var mtds = info.GetMethods(flags).Where(m => m.Name == name); foreach (var mtd in mtds) { var ps = mtd.GetParameters(); if (ps.Length != parameterTypes.Length) continue; var allMatch = true; for (var i = 0; i < ps.Length; i++) { var p = ps[i].ParameterType; var pt = parameterTypes[i]; if (p != pt) { allMatch = false; } } if (allMatch) { return mtd; } } return null; } }