System.Type.GetFields()

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

752 Examples 7

19 Source : RandomHelper.cs
with MIT License
from 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 Source : RandomHelper.cs
with MIT License
from 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 Source : InternalExtensions.cs
with MIT License
from 2881099

public static Dictionary<string, FieldInfo> GetFieldsDictIgnoreCase(this Type that) => that == null ? null : _dicGetFieldsDictIgnoreCase.GetOrAdd(that, tp =>
    {
        var fields = that.GetFields().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
        var dict = new Dictionary<string, FieldInfo>(StringComparer.CurrentCultureIgnoreCase);
        foreach (var field in fields)
        {
            if (dict.ContainsKey(field.Name)) dict[field.Name] = field;
            else dict.Add(field.Name, field);
        }
        return dict;
    });

19 Source : JsonMapper.cs
with MIT License
from 404Lcc

private static void AddObjectMetadata (Type type)
        {
            if (object_metadata.ContainsKey (type))
                return;

            ObjectMetadata data = new ObjectMetadata ();

            if (type.GetInterface ("System.Collections.IDictionary") != null)
                data.IsDictionary = true;

            data.Properties = new Dictionary<string, PropertyMetadata> ();
            foreach (PropertyInfo p_info in type.GetProperties ()) {
                if (Attribute.IsDefined(p_info, typeof(JsonIgnoreAttribute), true))
                    continue;
                if (p_info.Name == "Item") {
                    ParameterInfo[] parameters = p_info.GetIndexParameters ();

                    if (parameters.Length != 1)
                        continue;

                    if (parameters[0].ParameterType == typeof(string))
                    {
                        if (type is ILRuntime.Reflection.ILRuntimeWrapperType)
                        {
                            data.ElementType = ((ILRuntime.Reflection.ILRuntimeWrapperType)type).CLRType.GenericArguments[1].Value.ReflectionType;
                        }
                        else
                            data.ElementType = p_info.PropertyType;
                    }

                    continue;
                }

                PropertyMetadata p_data = new PropertyMetadata ();
                p_data.Info = p_info;
                p_data.Type = p_info.PropertyType;

                data.Properties.Add (p_info.Name, p_data);
            }

            foreach (FieldInfo f_info in type.GetFields ()) {
                if (Attribute.IsDefined(f_info, typeof(JsonIgnoreAttribute), true))
                    continue;
                PropertyMetadata p_data = new PropertyMetadata ();
                p_data.Info = f_info;
                p_data.IsField = true;
                p_data.Type = f_info.FieldType;

                data.Properties.Add (f_info.Name, p_data);
            }

            lock (object_metadata_lock) {
                try {
                    object_metadata.Add (type, data);
                } catch (ArgumentException) {
                    return;
                }
            }
        }

19 Source : JsonMapper.cs
with MIT License
from 404Lcc

private static void AddTypeProperties (Type type)
        {
            if (type_properties.ContainsKey (type))
                return;

            IList<PropertyMetadata> props = new List<PropertyMetadata> ();

            foreach (PropertyInfo p_info in type.GetProperties ()) {
                if (Attribute.IsDefined(p_info, typeof(JsonIgnoreAttribute), true))
                    continue;

                if (p_info.Name == "Item")
                    continue;

                PropertyMetadata p_data = new PropertyMetadata ();
                p_data.Info = p_info;
                p_data.IsField = false;
                props.Add (p_data);
            }

            foreach (FieldInfo f_info in type.GetFields ()) {
                if (Attribute.IsDefined(f_info, typeof(JsonIgnoreAttribute), true))
                    continue;

                PropertyMetadata p_data = new PropertyMetadata ();
                p_data.Info = f_info;
                p_data.IsField = true;

                props.Add (p_data);
            }

            lock (type_properties_lock) {
                try {
                    type_properties.Add (type, props);
                } catch (ArgumentException) {
                    return;
                }
            }
        }

19 Source : EnumExtensions.cs
with MIT License
from 52ABP

public static string ToEnumDescriptionString(this short value, Type enumType)
        {
            var nvc = new NameValueCollection();
            var typeDescription = typeof (DescriptionAttribute);
            var fields = enumType.GetFields();
            var strText = string.Empty;
            var strValue = string.Empty;
            foreach (var field in fields)
            {
                if (field.FieldType.IsEnum)
                {
                    strValue =
                        ((int) enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                    var arr = field.GetCustomAttributes(typeDescription, true);
                    if (arr.Length > 0)
                    {
                        var aa = (DescriptionAttribute) arr[0];
                        strText = aa.Description;
                    }
                    else
                    {
                        strText = "";
                    }
                    nvc.Add(strValue, strText);
                }
            }
            return nvc[value.ToString()];
        }

19 Source : JSONParser.cs
with MIT License
from 5minlab

static object ParseObject(Type type, string json) {
            object instance = FormatterServices.GetUninitializedObject(type);

            //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
            List<string> elems = Split(json);
            if (elems.Count % 2 != 0)
                return instance;

            Dictionary<string, FieldInfo> nameToField;
            Dictionary<string, PropertyInfo> nameToProperty;
            if (!fieldInfoCache.TryGetValue(type, out nameToField)) {
                nameToField = type.GetFields().Where(field => field.IsPublic).ToDictionary(field => field.Name);
                fieldInfoCache.Add(type, nameToField);
            }
            if (!propertyInfoCache.TryGetValue(type, out nameToProperty)) {
                nameToProperty = type.GetProperties().ToDictionary(p => p.Name);
                propertyInfoCache.Add(type, nameToProperty);
            }

            for (int i = 0; i < elems.Count; i += 2) {
                if (elems[i].Length <= 2)
                    continue;
                string key = elems[i].Substring(1, elems[i].Length - 2);
                string value = elems[i + 1];

                FieldInfo fieldInfo;
                PropertyInfo propertyInfo;
                if (nameToField.TryGetValue(key, out fieldInfo))
                    fieldInfo.SetValue(instance, ParseValue(fieldInfo.FieldType, value));
                else if (nameToProperty.TryGetValue(key, out propertyInfo))
                    propertyInfo.SetValue(instance, ParseValue(propertyInfo.PropertyType, value), null);
            }

            return instance;
        }

19 Source : ServerInformation.cs
with Apache License 2.0
from AantCoder

public ModelInfo GetInfo(ModelInt packet, ServiceContext context)
        {
            lock (context.Player)
            {
                switch (packet.Value)
                {
                    case (long)ServerInfoType.Full:
                        {
                            var result = GetModelInfo(context.Player);
                            return result;
                        }

                    case (long)ServerInfoType.SendSave:
                        {
                            if (context.PossiblyIntruder)
                            {
                                context.Disconnect("Possibly intruder");
                                return null;
                            }
                            var result = new ModelInfo();
                            //передача файла игры, для загрузки WorldLoad();
                            // файл передать можно только в том случае если файлы прошли проверку

                            //!Для Pvp проверка нужна всегда, в PvE нет
                            if (ServerManager.ServerSettings.IsModsWhitelisted)
                            {
                                if ((int)context.Player.ApproveLoadWorldReason > 0)
                                {
                                    context.Player.ExitReason = DisconnectReason.FilesMods;
                                    Loger.Log($"Login : {context.Player.Public.Login} not all files checked,{context.Player.ApproveLoadWorldReason.ToString() } Disconnect");
                                    result.SaveFileData = null;
                                    return result;
                                }
                            }

                            result.SaveFileData = Repository.GetSaveData.LoadPlayerData(context.Player.Public.Login, 1);

                            if (result.SaveFileData != null)
                            {
                                if (context.Player.MailsConfirmationSave.Count > 0)
                                {
                                    for (int i = 0; i < context.Player.MailsConfirmationSave.Count; i++) 
                                        context.Player.MailsConfirmationSave[i].NeedSaveGame = false;

                                    Loger.Log($"MailsConfirmationSave add {context.Player.MailsConfirmationSave.Count} (mails={context.Player.Mails.Count})");
                                    //Ого! Игрок не сохранился после приема письма, с обязательным сохранением после получения
                                    //Отправляем письма ещё раз
                                    if (context.Player.Mails.Count == 0)
                                    {
                                        context.Player.Mails = context.Player.MailsConfirmationSave.ToList();
                                    }
                                    else
                                    {
                                        var ms = context.Player.MailsConfirmationSave
                                            .Where(mcs => context.Player.Mails.Any(m => m.GetHashBase() != mcs.GetHashBase()))
                                            .ToList();
                                        context.Player.Mails.AddRange(ms);
                                    }
                                    Loger.Log($"MailsConfirmationSave (mails={context.Player.Mails.Count})");
                                }
                            }
                            Loger.Log($"Load World for {context.Player.Public.Login}. (mails={context.Player.Mails.Count}, fMails={context.Player.FunctionMails.Count})");

                            return result;
                        }

                    case (long)ServerInfoType.FullWithDescription:
                        {
                            var result = GetModelInfo(context.Player);
                            //result.Description = "";
                            var displayAttributes = new List<Tuple<int, string>>();

                            foreach (var prop in typeof(ServerSettings).GetFields())
                            {
                                var attribute = prop.GetCustomAttributes(typeof(DisplayAttribute)).FirstOrDefault();
                                if (attribute is null || !prop.IsPublic)
                                {
                                    continue;
                                }

                                var dispAtr = (DisplayAttribute)attribute;
                                var strvalue = string.IsNullOrEmpty(dispAtr.GetDescription()) ? prop.Name : dispAtr.GetDescription();
                                strvalue = strvalue + "=" + prop.GetValue(ServerManager.ServerSettings).ToString();
                                var order = dispAtr.GetOrder().HasValue ? dispAtr.GetOrder().Value : 0;
                                displayAttributes.Add(Tuple.Create(order, strvalue));
                            }

                            var sb = new StringBuilder();
                            var sorte = new List<string>(displayAttributes.OrderBy(x => x.Item1).Select(y => y.Item2)).AsReadOnly();
                            foreach (var prop in sorte)
                            {
                                sb.AppendLine(prop);
                            }

                            //result.Description = sb.ToString();
                            return result;
                        }
                    case (long)ServerInfoType.Short:
                    default:
                        {
                            // краткая (зарезервированно, пока не используется) fullInfo = false
                            var result = new ModelInfo();
                            return result;
                        }
                }
            }
        }

19 Source : InspectorFieldsUtility.cs
with Apache License 2.0
from abist-co-ltd

public static List<InspectorFieldData> GetInspectorFields(System.Object target)
        {
            List<InspectorFieldData> fields = new List<InspectorFieldData>();
            Type myType = target.GetType();

            foreach (PropertyInfo prop in myType.GetProperties())
            {
                var attrs = (InspectorField[])prop.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    fields.Add(new InspectorFieldData() { Name = prop.Name, Attributes = attr, Value = prop.GetValue(target, null) });
                }
            }

            foreach (FieldInfo field in myType.GetFields())
            {
                var attrs = (InspectorField[])field.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    fields.Add(new InspectorFieldData() { Name = field.Name, Attributes = attr, Value = field.GetValue(target) });
                }
            }

            return fields;
        }

19 Source : InspectorGenericFields.cs
with Apache License 2.0
from abist-co-ltd

public static void LoadSettings(T target, List<InspectorPropertySetting> settings)
        {
            Type myType = target.GetType();

            List<PropertyInfo> propInfoList = new List<PropertyInfo>(myType.GetProperties());
            for (int i = 0; i < propInfoList.Count; i++)
            {
                PropertyInfo propInfo = propInfoList[i];
                var attrs = (InspectorField[])propInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    object value = InspectorField.GetSettingValue(settings, propInfo.Name);
                    if (value != null)
                    {
                        propInfo.SetValue(target, value);
                    }
                }
            }

            List<FieldInfo> fieldInfoList = new List<FieldInfo>(myType.GetFields());
            for (int i = 0; i < fieldInfoList.Count; i++)
            {
                FieldInfo fieldInfo = fieldInfoList[i];
                var attrs = (InspectorField[])fieldInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    object value = InspectorField.GetSettingValue(settings, fieldInfo.Name);
                    if (value != null)
                    {
                        fieldInfo.SetValue(target, value);
                    }
                }
            }
        }

19 Source : InspectorGenericFields.cs
with Apache License 2.0
from abist-co-ltd

public static List<InspectorPropertySetting> GetSettings(T source)
        {
            Type myType = source.GetType();
            List<InspectorPropertySetting> settings = new List<InspectorPropertySetting>();

            List<PropertyInfo> propInfoList = new List<PropertyInfo>(myType.GetProperties());
            for (int i = 0; i < propInfoList.Count; i++)
            {
                PropertyInfo propInfo = propInfoList[i];
                var attrs = (InspectorField[])propInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    settings.Add(InspectorField.FieldToProperty(attr, propInfo.GetValue(source, null), propInfo.Name));
                }
            }

            List<FieldInfo> fieldInfoList = new List<FieldInfo>(myType.GetFields());
            for (int i = 0; i < fieldInfoList.Count; i++)
            {
                FieldInfo fieldInfo = fieldInfoList[i];
                var attrs = (InspectorField[])fieldInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    settings.Add(InspectorField.FieldToProperty(attr, fieldInfo.GetValue(source), fieldInfo.Name));
                }
            }

            return settings;
        }

19 Source : AssessmentProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static HashSet<TResult> GetValues<T, TResult>()
        {
            var list = typeof(T).GetFields().Select(x => new
            {
                att = x.GetCustomAttributes(false).OfType<replacedessmentPropertyAttribute>().FirstOrDefault(),
                member = x
            }).Where(x => x.att != null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();

            return new HashSet<TResult>(list);
        }

19 Source : ClientProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static HashSet<TResult> GetValues<T, TResult>()
        {
            var list =typeof(T).GetFields().Select(x => new
            {
                att = x.GetCustomAttributes(false).OfType<ServerOnlyAttribute>().FirstOrDefault(),
                member = x
            }).Where(x => x.att == null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();

            return new HashSet<TResult>(list);
        }

19 Source : EphemeralProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static HashSet<T> GetValues<T>()
        {
            var list = typeof(T).GetFields().Select(x => new
            {
                att = x.GetCustomAttributes(false).OfType<EphemeralAttribute>().FirstOrDefault(),
                member = x
            }).Where(x => x.att != null && x.member.Name != "value__").Select(x => (T)x.member.GetValue(null)).ToList();

            return new HashSet<T>(list);
        }

19 Source : SendOnLoginProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static HashSet<TResult> GetValues<T, TResult>()
        {
            var list = typeof(T).GetFields().Select(x => new
            {
                att = x.GetCustomAttributes(false).OfType<SendOnLoginAttribute>().FirstOrDefault(),
                member = x
            }).Where(x => x.att != null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();

            return new HashSet<TResult>(list);
        }

19 Source : ServerOnlyProperties.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static HashSet<TResult> GetValues<T, TResult>()
        {
            var list = typeof(T).GetFields().Select(x => new
            {
                att = x.GetCustomAttributes(false).OfType<ServerOnlyAttribute>().FirstOrDefault(),
                member = x
            }).Where(x => x.att != null && x.member.Name != "value__").Select(x => (TResult)x.member.GetValue(null)).ToList();

            return new HashSet<TResult>(list);
        }

19 Source : UnknownEnum.cs
with MIT License
from actions

public static object Parse(Type enumType, string stringValue)
        {
            var underlyingType = Nullable.GetUnderlyingType(enumType);
            enumType = underlyingType != null ? underlyingType : enumType;

            var names = Enum.GetNames(enumType);
            if (!string.IsNullOrEmpty(stringValue))
            {
                var match = names.FirstOrDefault(name => string.Equals(name, stringValue, StringComparison.OrdinalIgnoreCase));
                if (match != null)
                {
                    return Enum.Parse(enumType, match);
                }

                // maybe we have an enum member with an EnumMember attribute specifying a custom name
                foreach (var field in enumType.GetFields())
                {
                    var enumMemberAttribute = field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() as EnumMemberAttribute;
                    if (enumMemberAttribute != null && string.Equals(enumMemberAttribute.Value, stringValue, StringComparison.OrdinalIgnoreCase))
                    {
                        // we already have the field, no need to do enum.parse on it
                        return field.GetValue(null);
                    }
                }
            }

            return Enum.Parse(enumType, UnknownName);
        }

19 Source : FlagsEnum.cs
with MIT License
from actions

public static object ParseKnownFlags(Type enumType, string stringValue)
        {
            ArgumentUtility.CheckForNull(enumType, nameof(enumType));
            if (!enumType.IsEnum)
            {
                throw new ArgumentException(PipelinesWebApiResources.FlagEnumTypeRequired());
            }

            // Check for the flags attribute in debug. Skip this reflection in release.
            Debug.replacedert(enumType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any(), "FlagsEnum only intended for enums with the Flags attribute.");

            // The exception types below are based on Enum.TryParseEnum (http://index/?query=TryParseEnum&rightProject=mscorlib&file=system%5Cenum.cs&rightSymbol=bhaeh2vnegwo)
            if (stringValue == null)
            {
                throw new ArgumentNullException(stringValue);
            }

            if (String.IsNullOrWhiteSpace(stringValue))
            {
                throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
            }

            if (UInt64.TryParse(stringValue, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out ulong ulongValue))
            {
                return Enum.Parse(enumType, stringValue);
            }

            var enumNames = Enum.GetNames(enumType).ToHashSet(name => name, StringComparer.OrdinalIgnoreCase);
            var enumMemberMappings = new Lazy<IDictionary<string, string>>(() =>
            {
                IDictionary<string, string> mappings = null;
                foreach (var field in enumType.GetFields())
                {
                    if (field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() is EnumMemberAttribute enumMemberAttribute)
                    {
                        if (mappings == null)
                        {
                            mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                        }
                        mappings.Add(enumMemberAttribute.Value, field.GetValue(null).ToString());
                    }
                }

                return mappings;
            });

            var values = stringValue.Split(s_enumSeparatorCharArray);

            var matches = new List<string>();
            for (int i = 0; i < values.Length; i++)
            {
                string value = values[i].Trim();

                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
                }

                if (enumNames.Contains(value))
                {
                    matches.Add(value);
                }
                else if (enumMemberMappings.Value != null && enumMemberMappings.Value.TryGetValue(value, out string matchingValue))
                {
                    matches.Add(matchingValue);
                }
            }

            if (!matches.Any())
            {
                return Enum.Parse(enumType, "0");
            }

            string matchesString = String.Join(", ", matches);
            return Enum.Parse(enumType, matchesString, ignoreCase: true);
        }

19 Source : EnumDescriptionTypeConverter.cs
with MIT License
from Actipro

public static Object GetValue(Type type, String description) {
			FieldInfo[] fieldInfos = type.GetFields();
			foreach (FieldInfo fieldInfo in fieldInfos) {
				DescriptionAttribute[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
				if (null != attributes && 0 != attributes.Length) {
					if (attributes[0].Description == description)
						return fieldInfo.GetValue(fieldInfo.Name);
				}

				if (fieldInfo.Name == description)
					return fieldInfo.GetValue(fieldInfo.Name);
			}

			return description;
		}

19 Source : CustomIconProvider.android.cs
with MIT License
from adenearnshaw

private int GetId(string memberName)
        {
            var type = _drawableClreplaced;
            object value = type.GetFields().FirstOrDefault(p => p.Name == memberName)?.GetValue(type)
                           ?? type.GetProperties().FirstOrDefault(p => p.Name == memberName)?.GetValue(type);
            if (value is int)
                return (int)value;
            return 0;
        }

19 Source : ObjectShredder.cs
with MIT License
from Adoxio

public DataTable ExtendTable(DataTable table, Type type)
		{
			// Extend the table schema if the input table was null or if the value 
			// in the sequence is derived from type T.            
			foreach (FieldInfo f in type.GetFields())
			{
				if (!_ordinalMap.ContainsKey(f.Name))
				{
					var ft = f.FieldType;

					if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(Nullable<>))
					{
						ft = Nullable.GetUnderlyingType(ft);
					}

					// Add the field as a column in the table if it doesn't exist
					// already.
					DataColumn dc = table.Columns.Contains(f.Name)
						? table.Columns[f.Name]
						: table.Columns.Add(f.Name, ft);

					// Add the field to the ordinal map.
					_ordinalMap.Add(f.Name, dc.Ordinal);
				}
			}
			foreach (PropertyInfo p in type.GetProperties())
			{
				if (!_ordinalMap.ContainsKey(p.Name))
				{
					var pt = p.PropertyType;

					if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
					{
						pt = Nullable.GetUnderlyingType(pt);
					}

					// Add the property as a column in the table if it doesn't exist
					// already.
					DataColumn dc = table.Columns.Contains(p.Name)
						? table.Columns[p.Name]
						: table.Columns.Add(p.Name, pt);

					// Add the property to the ordinal map.
					_ordinalMap.Add(p.Name, dc.Ordinal);
				}
			}

			// Return the table.
			return table;
		}

19 Source : ObjectShredder.cs
with MIT License
from Adoxio

public object[] ShredObject(DataTable table, T instance)
		{
			FieldInfo[] fi = _fi;
			PropertyInfo[] pi = _pi;

			if (instance.GetType() != typeof(T))
			{
				// If the instance is derived from T, extend the table schema
				// and get the properties and fields.
				ExtendTable(table, instance.GetType());
				fi = instance.GetType().GetFields();
				pi = instance.GetType().GetProperties();
			}

			// Add the property and field values of the instance to an array.
			var values = new object[table.Columns.Count];
			foreach (FieldInfo f in fi)
			{
				values[_ordinalMap[f.Name]] = f.GetValue(instance);
			}

			foreach (PropertyInfo p in pi)
			{
				values[_ordinalMap[p.Name]] = p.GetValue(instance, null);
			}

			// Return the property and field values of the instance.
			return values;
		}

19 Source : EnumHelper.cs
with Mozilla Public License 2.0
from agebullhu

public static List<IEnumInfomation> GetEnumInfomation(Type type)
        {
            if (type == null)
            {
                return new List<IEnumInfomation>();
            }
            if (EnumInfomationMaps.ContainsKey(type))
            {
                return EnumInfomationMaps[type];
            }

            var enumFieldInfos = type.GetFields();
            var kvs = enumFieldInfos.Where(p => p.Name != "value__").Select(fieldInfo => (IEnumInfomation)new EnumInfomation
            {
                Caption = fieldInfo.GetDescription(),
                Value = Enum.Parse(type, fieldInfo.Name, true),
                LValue = Convert.ToInt64(Enum.Parse(type, fieldInfo.Name, true))
            }).ToList();

            EnumInfomationMaps.Add(type, kvs);

            return kvs;
        }

19 Source : EnumUtils.cs
with MIT License
from akaskela

private static BidirectionalDictionary<string, string> InitializeEnumType(Type type)
        {
            BidirectionalDictionary<string, string> map = new BidirectionalDictionary<string, string>(
                StringComparer.OrdinalIgnoreCase,
                StringComparer.OrdinalIgnoreCase);

            foreach (FieldInfo f in type.GetFields())
            {
                string n1 = f.Name;
                string n2;

#if !NET20
                n2 = f.GetCustomAttributes(typeof(EnumMemberAttribute), true)
                    .Cast<EnumMemberAttribute>()
                    .Select(a => a.Value)
                    .SingleOrDefault() ?? f.Name;
#else
                n2 = f.Name;
#endif

                string s;
                if (map.TryGetBySecond(n2, out s))
                {
                    throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, n2, type.Name));
                }

                map.Set(n1, n2);
            }

            return map;
        }

19 Source : EnumUtils.cs
with MIT License
from akaskela

public static IList<object> GetValues(Type enumType)
        {
            if (!enumType.IsEnum())
            {
                throw new ArgumentException("Type '" + enumType.Name + "' is not an enum.");
            }

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

            var fields = enumType.GetFields().Where(f => f.IsLiteral);

            foreach (FieldInfo field in fields)
            {
                object value = field.GetValue(enumType);
                values.Add(value);
            }

            return values;
        }

19 Source : EnumUtils.cs
with MIT License
from akaskela

public static IList<string> GetNames(Type enumType)
        {
            if (!enumType.IsEnum())
            {
                throw new ArgumentException("Type '" + enumType.Name + "' is not an enum.");
            }

            List<string> values = new List<string>();

            var fields = enumType.GetFields().Where(f => f.IsLiteral);

            foreach (FieldInfo field in fields)
            {
                values.Add(field.Name);
            }

            return values;
        }

19 Source : ObjectLists.cs
with MIT License
from AlFasGD

public static int[] GetNotGeneralObjectList()
        {
            List<int> objects = new List<int>();
            foreach (var f in typeof(ObjectLists).GetFields().Where(f => f.FieldType == typeof(int[]) && f.IsStatic))
                objects.AddRange((int[])f.GetRawConstantValue());
            objects.Sort();
            return objects.ToArray();
        }

19 Source : SongInformation.cs
with MIT License
from AlFasGD

private static ImmutableArray<string> GetAttributedFields<TAttribute>()
            where TAttribute : Attribute
        {
            return typeof(SongInformation).GetFields()
                .Where(f => f.GetCustomAttributes<TAttribute>().Any())
                .Select(f => f.GetRawConstantValue() as string)
                .ToImmutableArray();
        }

19 Source : EditorUI.cs
with MIT License
from allenwp

static void SubmitObjectInspector(object selectedObject)
        {
            ImGuiTreeNodeFlags collapsingHeaderFlags = ImGuiTreeNodeFlags.CollapsingHeader;
            collapsingHeaderFlags |= ImGuiTreeNodeFlags.DefaultOpen;

            var selectedType = selectedObject.GetType();

            if (ImGui.CollapsingHeader("Fields", collapsingHeaderFlags))
            {
                var fields = selectedType.GetFields();
                foreach (var info in fields.Where(field => !field.IsLiteral && !field.IsInitOnly))
                {
                    SubmitFieldPropertyInspector(new FieldPropertyListInfo(info, selectedObject), selectedObject);
                }
            }

            var properties = selectedType.GetProperties();

            if (ImGui.CollapsingHeader("Properties", collapsingHeaderFlags))
            {
                // When SetMethod is private, it will still be writable so long as it's clreplaced isn't inherited, so check to see if it's public too for the behaviour I want.
                foreach (var info in properties.Where(prop => prop.CanRead && prop.CanWrite && prop.SetMethod.IsPublic))
                {
                    SubmitFieldPropertyInspector(new FieldPropertyListInfo(info, selectedObject), selectedObject);
                }
            }

            if (ImGui.CollapsingHeader("Read-Only Properties", collapsingHeaderFlags))
            {
                // When SetMethod is private, it will still be writable so long as it's clreplaced isn't inherited, so check to see if it's public too for the behaviour I want.
                foreach (var info in properties.Where(prop => prop.CanRead && (!prop.CanWrite || !prop.SetMethod.IsPublic)))
                {
                    var fieldPropertyInfo = new FieldPropertyListInfo(info, selectedObject);
                    SubmitReadonlyFieldPropertyInspector(fieldPropertyInfo);
                    SubmitHelpMarker(fieldPropertyInfo);
                }
            }
        }

19 Source : BaseClone.cs
with MIT License
from alonsoalon

public object Clone()
        {
            //首先我们建立指定类型的一个实例
            object newObject = Activator.CreateInstance(this.GetType());
            //我们取得新的类型实例的字段数组。
            FieldInfo[] fields = newObject.GetType().GetFields();
            int i = 0;
            foreach (FieldInfo fi in this.GetType().GetFields())
            {
                //我们判断字段是否支持ICloneable接口。
                Type ICloneType = fi.FieldType.GetInterface("ICloneable", true);
                if (ICloneType != null)
                {
                    //取得对象的Icloneable接口。
                    ICloneable IClone = (ICloneable)fi.GetValue(this);
                    //我们使用克隆方法给字段设定新值。
                    fields[i].SetValue(newObject, IClone.Clone());
                }
                else
                {
                    // 如果该字段部支持Icloneable接口,直接设置即可。
                    fields[i].SetValue(newObject, fi.GetValue(this));
                }
                //现在我们检查该对象是否支持IEnumerable接口,如果支持,
                //我们还需要枚举其所有项并检查他们是否支持IList 或 IDictionary 接口。
                Type IEnumerableType = fi.FieldType.GetInterface("IEnumerable", true);
                if (IEnumerableType != null)
                {
                    //取得该字段的IEnumerable接口
                    IEnumerable IEnum = (IEnumerable)fi.GetValue(this);
                    Type IListType = fields[i].FieldType.GetInterface("IList", true);
                    Type IDicType = fields[i].FieldType.GetInterface("IDictionary", true);
                    int j = 0;
                    if (IListType != null)
                    {
                        //取得IList接口。
                        IList list = (IList)fields[i].GetValue(newObject);
                        foreach (object obj in IEnum)
                        {
                            //查看当前项是否支持支持ICloneable 接口。
                            ICloneType = obj.GetType().GetInterface("ICloneable", true);
                            if (ICloneType != null)
                            {
                                //如果支持ICloneable 接口,
                                //我们用它李设置列表中的对象的克隆
                                ICloneable clone = (ICloneable)obj;
                                list[j] = clone.Clone();

                            }
                            //注意:如果列表中的项不支持ICloneable接口,那么
                            //在克隆列表的项将与原列表对应项相同
                            //(只要该类型是引用类型)
                            j++;
                        }
                    }
                    else if (IDicType != null)
                    {
                        //取得IDictionary 接口
                        IDictionary dic = (IDictionary)fields[i].GetValue(newObject);
                        j = 0;
                        foreach (DictionaryEntry de in IEnum)
                        {
                            //查看当前项是否支持支持ICloneable 接口。
                            ICloneType = de.Value.GetType().
                            GetInterface("ICloneable", true);
                            if (ICloneType != null)
                            {
                                ICloneable clone = (ICloneable)de.Value;
                                dic[de.Key] = clone.Clone();
                            }
                            j++;
                        }
                    }
                }
                i++;
            }
            return newObject;
        }

19 Source : CacheAOPbase.cs
with Apache License 2.0
from anjoy8

private static string In(MethodCallExpression expression, object isTrue)
        {
            var Argument1 = (expression.Arguments[0] as MemberExpression).Expression as ConstantExpression;
            var Argument2 = expression.Arguments[1] as MemberExpression;
            var Field_Array = Argument1.Value.GetType().GetFields().First();
            object[] Array = Field_Array.GetValue(Argument1.Value) as object[];
            List<string> SetInPara = new List<string>();
            for (int i = 0; i < Array.Length; i++)
            {
                string Name_para = "InParameter" + i;
                string Value = Array[i].ToString();
                SetInPara.Add(Value);
            }
            string Name = Argument2.Member.Name;
            string Operator = Convert.ToBoolean(isTrue) ? "in" : " not in";
            string CompName = string.Join(",", SetInPara);
            string Result = $"{Name} {Operator} ({CompName})";
            return Result;
        }

19 Source : AnalyseDisplayViewModel.cs
with Apache License 2.0
from anmcgrath

private void SetNormalisationChoices()
        {
            var dcs = new DicomColors();
            var fields = typeof(DicomColors).GetFields();
            foreach (var field in fields)
                AvailableColors.Add((DicomColor)field.GetValue(dcs));

            RelativeNormalisationOptions = new List<RelativeNormalisationOption>()
            {
                RelativeNormalisationOption.Max,
                RelativeNormalisationOption.POI,
            };
            NormalisationTypes = new List<NormalisationType>()
            {
                NormalisationType.Relative,
                NormalisationType.Absolute
            };
            POIs = new ObservableCollection<PointOfInterest>();
        }

19 Source : JsonMapper.cs
with MIT License
from AnotherEnd15

private static void AddObjectMetadata(Type type)
        {
            if (object_metadata.ContainsKey(type))
                return;

            ObjectMetadata data = new ObjectMetadata();

            if (type.GetInterface("System.Collections.IDictionary") != null)
                data.IsDictionary = true;

            data.Properties = new Dictionary<string, PropertyMetadata>();

            foreach (PropertyInfo p_info in type.GetProperties())
            {
                if (p_info.Name == "Item")
                {
                    ParameterInfo[] parameters = p_info.GetIndexParameters();

                    if (parameters.Length != 1)
                        continue;

                    if (parameters[0].ParameterType == typeof (string))
                        data.ElementType = p_info.PropertyType;

                    continue;
                }

                PropertyMetadata p_data = new PropertyMetadata();
                p_data.Info = p_info;
                p_data.Type = p_info.PropertyType;

                data.Properties.Add(p_info.Name, p_data);
            }

            foreach (FieldInfo f_info in type.GetFields())
            {
                PropertyMetadata p_data = new PropertyMetadata();
                p_data.Info = f_info;
                p_data.IsField = true;
                p_data.Type = f_info.FieldType;

                data.Properties.Add(f_info.Name, p_data);
            }

            lock (object_metadata_lock)
            {
                try
                {
                    object_metadata.Add(type, data);
                }
                catch (ArgumentException)
                {
                    return;
                }
            }
        }

19 Source : JsonMapper.cs
with MIT License
from AnotherEnd15

private static void AddTypeProperties(Type type)
        {
            if (type_properties.ContainsKey(type))
                return;

            IList<PropertyMetadata> props = new List<PropertyMetadata>();

            foreach (PropertyInfo p_info in type.GetProperties())
            {
                if (p_info.Name == "Item")
                    continue;

                PropertyMetadata p_data = new PropertyMetadata();
                p_data.Info = p_info;
                p_data.IsField = false;
                props.Add(p_data);
            }

            foreach (FieldInfo f_info in type.GetFields())
            {
                PropertyMetadata p_data = new PropertyMetadata();
                p_data.Info = f_info;
                p_data.IsField = true;

                props.Add(p_data);
            }

            lock (type_properties_lock)
            {
                try
                {
                    type_properties.Add(type, props);
                }
                catch (ArgumentException)
                {
                    return;
                }
            }
        }

19 Source : ItemId.cs
with Apache License 2.0
from anpShawn

public static void CacheIds()
    {
        validIds = new List<string>();

        Type t = typeof(ItemId);
        Type tString = typeof(string);
        FieldInfo[] fields = t.GetFields();
        FieldInfo f;
        for(int i=0; i< fields.Length; i++)
        {
            f = fields[i];
            if(f.IsStatic && f.IsPublic && f.FieldType == tString)
            {
                validIds.Add( (string)f.GetValue(null) );
            }
        }
    }

19 Source : SkillId.cs
with Apache License 2.0
from anpShawn

public static void CacheIds()
    {
        validIds = new List<string>();

        Type t = typeof(SkillId);
        Type tString = typeof(string);
        FieldInfo[] fields = t.GetFields();
        FieldInfo f;
        for(int i=0; i< fields.Length; i++)
        {
            f = fields[i];
            if(f.IsStatic && f.IsPublic && f.FieldType == tString)
            {
                validIds.Add( (string)f.GetValue(null) );
                //Main.Trace(f.GetValue(null));
            }
        }
    }

19 Source : Stats.cs
with Apache License 2.0
from anpShawn

public static void BuildDefaultStats()
    {
        //use reflection to build a list of default stats based on what the Stat type contains
        defaultStats = new Dictionary<string, long>();

        Type typeStat = typeof(Stat);
        Type typeString = typeof(string);
        FieldInfo[] statFields = typeStat.GetFields();
        FieldInfo curFieldInfo;
        string curKey;

        nonbasicKeys = new List<string>();

        for(int i = 0; i< statFields.Length; i++)
        {
            curFieldInfo = statFields[i];

            if(curFieldInfo.FieldType == typeString)
            {
                curKey = curFieldInfo.GetValue(null).ToString();
                defaultStats.Add(curKey, 0);

                //also build nonbasic stat keys while here
                if (curKey != Stat.hp && curKey != Stat.mp && curKey != Stat.atk && curKey != Stat.max_hp && curKey != Stat.max_mp)
                    nonbasicKeys.Add(curKey);
            }
        }

        percentageBasedKeys = new List<string>() { Stat.crit_bonus, Stat.crit_chance, Stat.magic_boost, Stat.gold_find, Stat.essence_find, Stat.chance_for_dungeon_keys, Stat.evade,
                                                    Stat.dmg_reduction, Stat.dmg_reflection, Stat.status_resist, Stat.chance_to_psn, Stat.chance_to_burn, Stat.chance_to_stun, Stat.chance_for_food, Stat.mastery_xp_boost,
                                                    Stat.atk_boost, Stat.mp_boost, Stat.hp_boost, Stat.phys_boost};

        wholePartyKeys = new string[] { Stat.gold_find, Stat.item_find, Stat.essence_find, Stat.chance_for_dungeon_keys, Stat.mastery_xp_boost, Stat.ore_find, Stat.gold_multiplier };
    }

19 Source : Utils.cs
with Apache License 2.0
from AnthonyLloyd

static string PrintFields(object o)
        {
            var sb = new StringBuilder("(");
            var fields = o.GetType().GetFields();
            sb.Append(Print(fields[0].GetValue(o)));
            for (int i = 1; i < fields.Length; i++)
            {
                sb.Append(", ");
                sb.Append(Print(fields[i].GetValue(o)));
            }
            sb.Append(")");
            return sb.ToString();
        }

19 Source : H5Utils.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

public static unsafe T[] ReadCompound<T>(
            DatatypeMessage datatype,
            DataspaceMessage dataspace,
            Superblock superblock,
            Span<byte> data,
            Func<FieldInfo, string> getName) where T : struct
        {
            if (datatype.Clreplaced != DatatypeMessageClreplaced.Compound)
                throw new Exception($"This method can only be used for data type clreplaced '{DatatypeMessageClreplaced.Compound}'.");

            var type = typeof(T);
            var fieldInfoMap = new Dictionary<string, FieldProperties>();

            foreach (var fieldInfo in type.GetFields())
            {
                var name = getName(fieldInfo);

                var isNotSupported = H5Utils.IsReferenceOrContainsReferences(fieldInfo.FieldType)
                                  && fieldInfo.FieldType != typeof(string);

                if (isNotSupported)
                    throw new Exception("Nested nullable fields are not supported.");

                fieldInfoMap[name] = new FieldProperties()
                {
                    FieldInfo = fieldInfo,
                    Offset = Marshal.OffsetOf(type, fieldInfo.Name)
                };
            }

            var properties = datatype.Properties
                .Cast<CompoundPropertyDescription>()
                .ToList();

            var sourceOffset = 0UL;
            var sourceRawBytes = data;
            var sourceElementSize = datatype.Size;

            var targetArraySize = H5Utils.CalculateSize(dataspace.DimensionSizes, dataspace.Type);
            var targetArray = new T[targetArraySize];
            var targetElementSize = Marshal.SizeOf<T>();

            for (int i = 0; i < targetArray.Length; i++)
            {
                var targetRawBytes = new byte[targetElementSize];
                var stringMap = new Dictionary<FieldProperties, string>();

                foreach (var property in properties)
                {
                    if (!fieldInfoMap.TryGetValue(property.Name, out var fieldInfo))
                        throw new Exception($"The property named '{property.Name}' in the HDF5 data type does not exist in the provided structure of type '{typeof(T)}'.");

                    var fieldSize = (int)property.MemberTypeMessage.Size;

                    // strings
                    if (fieldInfo.FieldInfo.FieldType == typeof(string))
                    {
                        var sourceIndex = (int)(sourceOffset + property.MemberByteOffset);
                        var sourceIndexEnd = sourceIndex + fieldSize;
                        var targetIndex = fieldInfo.Offset.ToInt64();
                        var value = H5Utils.ReadString(property.MemberTypeMessage, sourceRawBytes[sourceIndex..sourceIndexEnd], superblock);

                        stringMap[fieldInfo] = value[0];
                    }
                    // other value types
                    else
                    {
                        for (uint j = 0; j < fieldSize; j++)
                        {
                            var sourceIndex = sourceOffset + property.MemberByteOffset + j;
                            var targetIndex = fieldInfo.Offset.ToInt64() + j;

                            targetRawBytes[targetIndex] = sourceRawBytes[(int)sourceIndex];
                        }
                    }
                }

                sourceOffset += sourceElementSize;

                fixed (byte* ptr = targetRawBytes.replacedpan())
                {
                    // http://benbowen.blog/post/fun_with_makeref/
                    // https://stackoverflow.com/questions/4764573/why-is-typedreference-behind-the-scenes-its-so-fast-and-safe-almost-magical
                    // Both do not work because struct layout is different with __makeref:
                    // https://stackoverflow.com/questions/1918037/layout-of-net-value-type-in-memory
                    targetArray[i] = Marshal.PtrToStructure<T>(new IntPtr(ptr));

                    foreach (var entry in stringMap)
                    {
                        var reference = __makeref(targetArray[i]);
                        entry.Key.FieldInfo.SetValueDirect(reference, entry.Value);
                    }
                }
            }

            return targetArray;
        }

19 Source : TestUtils.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

private static long GetHdfTypeIdFromType(Type type)
        {
            var elementType = type.IsArray ? type.GetElementType() : type;

            if (elementType == typeof(bool))
                return H5T.NATIVE_UINT8;

            else if (elementType == typeof(byte))
                return H5T.NATIVE_UINT8;

            else if (elementType == typeof(sbyte))
                return H5T.NATIVE_INT8;

            else if (elementType == typeof(ushort))
                return H5T.NATIVE_UINT16;

            else if (elementType == typeof(short))
                return H5T.NATIVE_INT16;

            else if (elementType == typeof(uint))
                return H5T.NATIVE_UINT32;

            else if (elementType == typeof(int))
                return H5T.NATIVE_INT32;

            else if (elementType == typeof(ulong))
                return H5T.NATIVE_UINT64;

            else if (elementType == typeof(long))
                return H5T.NATIVE_INT64;

            else if (elementType == typeof(float))
                return H5T.NATIVE_FLOAT;

            else if (elementType == typeof(double))
                return H5T.NATIVE_DOUBLE;

            // issues: https://en.wikipedia.org/wiki/Long_double
            //else if (elementType == typeof(decimal))
            //    return H5T.NATIVE_LDOUBLE;

            else if (elementType.IsEnum)
            {
                var baseTypeId = TestUtils.GetHdfTypeIdFromType(Enum.GetUnderlyingType(elementType));
                var typeId = H5T.enum_create(baseTypeId);

                foreach (var value in Enum.GetValues(type))
                {
                    var value_converted = Convert.ToInt64(value);
                    var name = Enum.GetName(type, value_converted);

                    var handle = GCHandle.Alloc(value_converted, GCHandleType.Pinned);
                    H5T.enum_insert(typeId, name, handle.AddrOfPinnedObject());
                }

                return typeId;
            }

            else if (elementType == typeof(string) || elementType == typeof(IntPtr))
            {
                var typeId = H5T.copy(H5T.C_S1);

                H5T.set_size(typeId, H5T.VARIABLE);
                H5T.set_cset(typeId, H5T.cset_t.UTF8);

                return typeId;
            }
            else if (elementType.IsValueType && !elementType.IsPrimitive)
            {
                var typeId = H5T.create(H5T.clreplaced_t.COMPOUND, new IntPtr(Marshal.SizeOf(elementType)));

                foreach (var fieldInfo in elementType.GetFields())
                {
                    var fieldType = TestUtils.GetHdfTypeIdFromType(fieldInfo.FieldType);
                    var attribute = fieldInfo.GetCustomAttribute<H5NameAttribute>(true);
                    var hdfFieldName = attribute is not null ? attribute.Name : fieldInfo.Name;

                    H5T.insert(typeId, hdfFieldName, Marshal.OffsetOf(elementType, fieldInfo.Name), fieldType);

                    if (H5I.is_valid(fieldType) > 0)
                        H5T.close(fieldType);
                }

                return typeId;
            }
            else
            {
                throw new NotSupportedException();
            }
        }

19 Source : WorkSheet.cs
with Apache License 2.0
from Appdynamics

public void LoadFromCollectionTest()
        {
            var ws = _pck.Workbook.Worksheets.Add("LoadFromCollection");
            List<TestDTO> list = new List<TestDTO>();
            list.Add(new TestDTO() { Id = 1, Name = "Item1", Boolean = false, Date = new DateTime(2011, 1, 1), dto = null, NameVar = "Field 1" });
            list.Add(new TestDTO() { Id = 2, Name = "Item2", Boolean = true, Date = new DateTime(2011, 1, 15), dto = new TestDTO(), NameVar = "Field 2" });
            list.Add(new TestDTO() { Id = 3, Name = "Item3", Boolean = false, Date = new DateTime(2011, 2, 1), dto = null, NameVar = "Field 3" });
            list.Add(new TestDTO() { Id = 4, Name = "Item4", Boolean = true, Date = new DateTime(2011, 4, 19), dto = list[1], NameVar = "Field 4" });
            list.Add(new TestDTO() { Id = 5, Name = "Item5", Boolean = false, Date = new DateTime(2011, 5, 8), dto = null, NameVar = "Field 5" });
            list.Add(new TestDTO() { Id = 6, Name = "Item6", Boolean = true, Date = new DateTime(2010, 3, 27), dto = null, NameVar = "Field 6" });
            list.Add(new TestDTO() { Id = 7, Name = "Item7", Boolean = false, Date = new DateTime(2009, 1, 5), dto = list[3], NameVar = "Field 7" });
            list.Add(new TestDTO() { Id = 8, Name = "Item8", Boolean = true, Date = new DateTime(2018, 12, 31), dto = null, NameVar = "Field 8" });
            list.Add(new TestDTO() { Id = 9, Name = "Item9", Boolean = false, Date = new DateTime(2010, 2, 1), dto = null, NameVar = "Field 9" });

            ws.Cells["A1"].LoadFromCollection(list, true);
            ws.Cells["A30"].LoadFromCollection(list, true, OfficeOpenXml.Table.TableStyles.Medium9, BindingFlags.Instance | BindingFlags.Instance, typeof(TestDTO).GetFields());

            ws.Cells["A45"].LoadFromCollection(list, true, OfficeOpenXml.Table.TableStyles.Light1, BindingFlags.Instance | BindingFlags.Instance, new MemberInfo[] { typeof(TestDTO).GetMethod("GetNameID"), typeof(TestDTO).GetField("NameVar") });
            ws.Cells["J1"].LoadFromCollection(from l in list where l.Boolean orderby l.Date select new { Name = l.Name, Id = l.Id, Date = l.Date, NameVariable = l.NameVar }, true, OfficeOpenXml.Table.TableStyles.Dark4);

            var ints = new int[] { 1, 3, 4, 76, 2, 5 };
            ws.Cells["A15"].Value = ints;

            ws = _pck.Workbook.Worksheets.Add("LoadFromCollection_Inherited");
            List<InheritTestDTO> inhList = new List<InheritTestDTO>();
            inhList.Add(new InheritTestDTO() { Id = 1, Name = "Item1", Boolean = false, Date = new DateTime(2011, 1, 1), dto = null, NameVar = "Field 1", InheritedProp="Inherited 1" });
            inhList.Add(new InheritTestDTO() { Id = 2, Name = "Item2", Boolean = true, Date = new DateTime(2011, 1, 15), dto = new TestDTO(), NameVar = "Field 2", InheritedProp = "Inherited 2" });
            ws.Cells["A1"].LoadFromCollection(inhList, true);
            replacedert.AreEqual("Inherited 2", ws.Cells[3, 1].Value);

            ws.Cells["A5"].LoadFromCollection(inhList, true, TableStyles.None, BindingFlags.Public | BindingFlags.Instance, new MemberInfo[]{typeof(InheritTestDTO).GetProperty("InheritedProp"), typeof(TestDTO).GetProperty("Name") });
            replacedert.AreEqual("Inherited 2", ws.Cells[7, 1].Value);

        }

19 Source : WorkSheet.cs
with Apache License 2.0
from Appdynamics

public void LoadFromEmptyCollectionTest()
        {
            if (_pck == null) _pck = new ExcelPackage();
            var ws = _pck.Workbook.Worksheets.Add("LoadFromEmpyCollection");
            List<TestDTO> listDTO = new List<TestDTO>(0);
            //List<int> list = new List<int>(0);

            ws.Cells["A1"].LoadFromCollection(listDTO, true);
            ws.Cells["A5"].LoadFromCollection(listDTO, true, OfficeOpenXml.Table.TableStyles.Medium9, BindingFlags.Instance | BindingFlags.Instance, typeof(TestDTO).GetFields());

            ws.Cells["A10"].LoadFromCollection(listDTO, true, OfficeOpenXml.Table.TableStyles.Light1, BindingFlags.Instance | BindingFlags.Instance, new MemberInfo[] { typeof(TestDTO).GetMethod("GetNameID"), typeof(TestDTO).GetField("NameVar") });
            ws.Cells["A15"].LoadFromCollection(from l in listDTO where l.Boolean orderby l.Date select new { Name = l.Name, Id = l.Id, Date = l.Date, NameVariable = l.NameVar }, true, OfficeOpenXml.Table.TableStyles.Dark4);

            ws.Cells["A20"].LoadFromCollection(listDTO, false);
        }

19 Source : PlanetProfile.cs
with MIT License
from Arghonot

public Graph.GenericDicionnary GetArguments()
    {
        Graph.GenericDicionnary gd = new Graph.GenericDicionnary();

        foreach (var item in this.GetType().GetFields())
        {
            gd.Add(item.Name, item.GetValue(this));
            //if (item.Name == "frequency") Debug.Log(item.Name + " " + (double)item.GetValue(this));
        }

        //Debug.Log("there are : " + gd.Count.ToString() + " keys in the dictionnary");

        return gd;
    }

19 Source : ShredObjectToDataTable.cs
with MIT License
from ARKlab

public object[] ShredObject(DataTable table, T instance)
        {

            FieldInfo[] fi = _fi;
            PropertyInfo[] pi = _pi;

            if (instance.GetType() != typeof(T))
            {
                // If the instance is derived from T, extend the table schema 
                // and get the properties and fields.
                ExtendTable(table, instance.GetType());
                fi = instance.GetType().GetFields();
                pi = instance.GetType().GetProperties();
            }

            // Add the property and field values of the instance to an array.
            object[] values = new object[table.Columns.Count];
            foreach (FieldInfo f in fi)
            {
                values[_ordinalMap[f.Name]] = _convertColumnValue(f.GetValue(instance));
            }

            foreach (PropertyInfo p in pi)
            {
                values[_ordinalMap[p.Name]] = _convertColumnValue(p.GetValue(instance, null));
            }

            // Return the property and field values of the instance. 
            return values;
        }

19 Source : ShredObjectToDataTable.cs
with MIT License
from ARKlab

public DataTable ExtendTable(DataTable table, Type type)
        {
            // Extend the table schema if the input table was null or if the value  
            // in the sequence is derived from type T.             
            foreach (FieldInfo f in type.GetFields())
            {
                if (!_ordinalMap.ContainsKey(f.Name))
                {
                    var t = _deriveColumnType(f.FieldType);

                    // Add the field as a column in the table if it doesn't exist 
                    // already.
                    DataColumn dc = table.Columns.Contains(f.Name) ? table.Columns[f.Name]
                        : table.Columns.Add(f.Name, t);

                    // Add the field to the ordinal map.
                    _ordinalMap.Add(f.Name, dc.Ordinal);
                }
            }
            foreach (PropertyInfo p in type.GetProperties())
            {
                if (!_ordinalMap.ContainsKey(p.Name))
                {
                    var t = _deriveColumnType(p.PropertyType);

                    // Add the property as a column in the table if it doesn't exist 
                    // already.
                    DataColumn dc = table.Columns.Contains(p.Name) ? table.Columns[p.Name]
                        : table.Columns.Add(p.Name, t);

                    // Add the property to the ordinal map.
                    _ordinalMap.Add(p.Name, dc.Ordinal);
                }
            }

            // Return the table. 
            return table;
        }

19 Source : TrainingCatalog.cs
with MIT License
from aslotte

public async Task LogHyperParametersAsync<T>(Guid runId, T trainer) where T : clreplaced
        {
            var trainerType = trainer.GetType();
            // All trainers have an Options object which is used to set the parameters for the training.
            var trainerField = trainerType.GetRuntimeFields().FirstOrDefault(f => f.Name.Contains("Options"));
            if (trainerField != null)
            {
                var options = Dynamic.InvokeGet(trainer, trainerField.Name);
                foreach (var optionField in trainerField.FieldType.GetFields())
                {
                    // Tracking only primitive types as of now
                    if (optionField.FieldType.IsPrimitive || optionField.FieldType == typeof(Decimal) || optionField.FieldType == typeof(String))
                    {
                        var value = optionField.GetValue(options);
                        if (value != null)
                            await hyperParameterRepository.LogHyperParameterAsync(runId, optionField.Name, value.ToString());
                    }
                }
            }
        }

19 Source : Export.cs
with MIT License
from atenfyr

private static void InitAllFields()
        {
            if (_allFields != null) return;
            _allFields = typeof(Export).GetFields().Where(fld => fld.IsDefined(typeof(FObjectExportFieldAttribute), true)).OrderBy(fld => ((FObjectExportFieldAttribute[])fld.GetCustomAttributes(typeof(FObjectExportFieldAttribute), true))[0].DisplayingIndex).ToArray();
        }

19 Source : FsmManager.cs
with GNU General Public License v3.0
from Athlon007

public static void ResetAll()
        {
            FieldInfo[] fields = typeof(FsmManager).GetFields();
            // Loop through fields
            foreach (var field in fields)
            {
                field.SetValue(field, null);
            }
        }

19 Source : ConsoleCommands.cs
with GNU General Public License v3.0
from Athlon007

public override void Run(string[] args)
        {
            if (args.Length == 0)
            {
                ModConsole.Log("See \"mop help\" for command list.");
                return;
            }

            switch (args[0])
            {
                default:
                    ModConsole.Log("Invalid command. Type \"mop help\" for command list.");
                    break;
                case "help":
                    if (args.Length > 1)
                    {
                        string[] helpList = HelpList.Split('\n');
                        bool commandsFound = false;
                        foreach (string s in helpList)
                        {
                            if (s.Split('-')[0].Contains(args[1]))
                            {
                                ModConsole.Log(s);
                                commandsFound = true;
                            }
                        }
                        if (!commandsFound)
                            ModConsole.Log($"Command {args[1]} not found.");
                        return;
                    }
                    ModConsole.Log(HelpList);
                    break;
                case "rules":
                    if (args.Length > 1 && args[1] == "roll")
                    {
                        ModConsole.Log("\n<color=yellow>You know the rules and so do I\n" +
                                        "A full commitment's what I'm thinking of\n" +
                                        "You wouldn't get this from any other guy\n" +
                                        "I just wanna tell you how I'm feeling\n" +
                                        "Gotta make you understand\n" +
                                        "Never gonna give you up\n" +
                                        "Never gonna let you down\n" +
                                        "Never gonna run around and desert you\n" +
                                        "Never gonna make you cry\n" +
                                        "Never gonna say goodbye\n" +
                                        "Never gonna tell a lie and hurt you</color>\n\n");
                        return;
                    }

                    if (RulesManager.Instance.IgnoreRules.Count > 0)
                    {
                        ModConsole.Log("<color=yellow><b>Ignore Rules</b></color>");
                        foreach (IgnoreRule r in RulesManager.Instance.IgnoreRules)
                            ModConsole.Log($"<b>Object:</b> {r.ObjectName}");
                    }

                    if (RulesManager.Instance.IgnoreRulesAtPlaces.Count > 0)
                        {
                        ModConsole.Log("\n<color=yellow><b>Ignore Rules At Place</b></color>");
                        foreach (IgnoreRuleAtPlace r in RulesManager.Instance.IgnoreRulesAtPlaces)
                            ModConsole.Log($"<b>Place:</b> {r.Place} <b>Object:</b> {r.ObjectName}");
                    }

                    if (RulesManager.Instance.ToggleRules.Count > 0)
                    {
                        ModConsole.Log("\n<color=yellow><b>Toggle Rules</b></color>");
                        foreach (ToggleRule r in RulesManager.Instance.ToggleRules)
                            ModConsole.Log($"<b>Object:</b> {r.ObjectName} <b>Toggle Mode:</b> {r.ToggleMode}");
                    }

                    if (RulesManager.Instance.NewSectors.Count > 0)
                    {
                        ModConsole.Log("\n<color=yellow><b>New Sectors</b></color>");
                        foreach (NewSector r in RulesManager.Instance.NewSectors)
                            ModConsole.Log($"<b>Pos:</b> {r.Position} <b>Scale:</b> {r.Scale} <b>Rot:</b> {r.Rotation} <b>Ignore:</b> {string.Join(", ", r.Whitelist)}");
                    }

                    ModConsole.Log("\n<color=yellow><b>Special Rules</b></color>");
                    // Obtain all fields
                    FieldInfo[] fields = typeof(SpecialRules).GetFields();
                    // Loop through fields
                    foreach (var field in fields) 
                    {
                        ModConsole.Log($"<b>{field.Name}</b>: {field.GetValue(RulesManager.Instance.SpecialRules)}");
                    }

                    // List rule files.
                    string output = "\n<color=yellow><b>Rule Files</b></color>\n";
                    foreach (string ruleFile in RulesManager.Instance.RuleFileNames)
                        output += $"{ruleFile}\n";

                    ModConsole.Log(output);
                    break;
                case "reload":
                    if (ModLoader.CurrentScene != CurrentScene.MainMenu)
                    {
                        ModConsole.Log("You can only reload rule files in the main menu");
                        return;
                    }

                    RulesManager.Instance.WipeAll(false);
                    break;
                case "new":
                    string path = $"{MOP.ModConfigPath}/Custom.txt";

                    if (args.Length > 1)
                    {
                        path = $"{MOP.ModConfigPath}/{args[1]}.mopconfig";
                    }

                    if (File.Exists(path))
                    {
                        ModConsole.Log("Custom file already exists. Use \"mop open\" to edit it now.");
                        return;
                    }

                    File.WriteAllText(path, "## Every line which starts with ## will be ignored.\n" +
                                            "## All new flags MUST be written in a new line.\n" +
                                            "## Visit http://athlon.kkmr.pl/mop/wiki/#/rulefiles_commands for doreplacedentation.\n" +
                                            "## WARNING: Using custom rule files may cause issues. Use only at your own risk!");

                    Process.Start(path);
                    if (path.EndsWith("Custom.txt"))
                    {
                        ModConsole.Log("A custom rule file has been created. You can find it as Custom.txt.\n" +
                            "<color=red>Careless use of rule files may cause bugs and glitchess. Use only at yout own risk!</color>");
                    }
                    else
                    {
                        ModConsole.Log($"A rule file for {args[1]} mod has been created.");
                    }
                    break;
                case "version":
                    ModConsole.Log(MOP.ModVersion);
                    break;
                case "cowsay":
                    string say = string.Join(" ", args, 1, args.Length - 1);

                    switch (say.ToLower())
                    {
                        case "tell me your secrets":
                            say = "all pls fix and no appreciation makes Athlon an angry boy";
                            break;
                        case "tell me your wisdoms":
                            say = "people saying that MOP is just improved KruFPS are straight up wrong";
                            break;
                        case "wieski":
                            say = "it really do be like dat doe sometimes";
                            break;
                        case "embu":
                            say = "pee vee good";
                            break;
                        case "owo":
                            say = "UwU";
                            break;
                        case "uwu":
                            say = "OwO";
                            break;
                        case "mop sucks":
                            say = "no u";
                            Process.Start("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
                            break;
                    }

                    ModConsole.Log($"< {say} >\n" +
                                    "        \\   ^__^\n" +
                                    "         \\  (oo)\\____\n" +
                                    "            (__)\\          )\\/\\\n" +
                                    "                ||  ----w  |\n" +
                                    "                ||           || ");
                    break;
                case "open-config":
                    Process.Start(MOP.ModConfigPath);
                    break;
                case "open":
                    if (args.Length == 1)
                    {
                        ModConsole.Log($"Missing argument.");
                        return;
                    }

                    if (args[1].StartsWith("Custom") || args[1].StartsWith("custom"))
                    {
                        if (!args[1].EndsWith(".txt"))
                            args[1] += ".txt";
                    }
                    else
                    {
                        if (!args[1].EndsWith(".mopconfig"))
                            args[1] += ".mopconfig";
                    }

                    if (!File.Exists($"{MOP.ModConfigPath}/{args[1]}"))
                    { 
                        ModConsole.Log($"File {args[1]} doesn't exist.");
                        return;
                    }

                    Process.Start($"{MOP.ModConfigPath}/{args[1]}");
                    break;
                case "delete":
                    if (args.Length == 1)
                    {
                        ModConsole.Log($"Missing argument.");
                        return;
                    }

                    if (args[1].StartsWith("Custom") && !args[1].EndsWith(".txt"))
                    {
                        args[1] += ".txt";
                    }
                    else
                    {
                        if (!args[1].EndsWith(".mopconfig"))
                            args[1] += ".mopconfig";
                    }

                    if (!File.Exists($"{MOP.ModConfigPath}/{args[1]}"))
                    {
                        ModConsole.Log($"File {args[1]} doesn't exist.");
                        return;
                    }

                    File.Delete($"{MOP.ModConfigPath}/{args[1]}");
                    break;
                case "cat":
                    if (args.Length == 1)
                    {
                        ModConsole.Log($"Missing argument.");
                        return;
                    }

                    if (args[1].StartsWith("Custom") && !args[1].EndsWith(".txt"))
                    {
                        args[1] += ".txt";
                    }
                    else
                    {
                        if (!args[1].EndsWith(".mopconfig"))
                            args[1] += ".mopconfig";
                    }

                    if (!File.Exists($"{MOP.ModConfigPath}/{args[1]}"))
                    {
                        ModConsole.Log($"File {args[1]} doesn't exist.");
                        return;
                    }

                    ModConsole.Log(File.ReadAllText($"{MOP.ModConfigPath}/{args[1]}"));
                    break;
                case "generate-list":
                    if (args.Length > 1)
                    {
                        if (RulesManager.Instance.LoadRules && 
                            (RulesManager.Instance.IgnoreRules.Count > 0 || RulesManager.Instance.IgnoreRulesAtPlaces.Count > 0 ||
                             RulesManager.Instance.NewSectors.Count > 0 || RulesManager.Instance.ToggleRules.Count > 0)
                            )
                        {
                            ModConsole.Log("<color=red>WARNING:</color> For accurate results, use \"mop load-rules false\" to prevent MOP from using rule files.");
                        }

                        MopSettings.GenerateToggledItemsListDebug = args[1].ToLower() == "true";
                    }

                    ModConsole.Log($"Generating toggled elements list is set to " +
                                     $"<color={(MopSettings.GenerateToggledItemsListDebug ? "green" : "red")}>{MopSettings.GenerateToggledItemsListDebug}</color>");
                    break;
                case "load-rules":
                    if (args.Length > 1)
                    {
                        RulesManager.Instance.LoadRules = args[1].ToLower() == "true";
                        if (!RulesManager.Instance.LoadRules)
                        {
                            ModConsole.Log("\n\n<color=red>WARNING:</color>\nDisabling rule files may cause serious issues with game, or even break your game save.\n\n" +
                                             "<b><color=red>!!! USE ONLY AT YOUR OWN RISK !!!</color></b>\n\n");
                        }
                    }

                    ModConsole.Log($"Loading rule files is set to " +
                                     $"<color={(RulesManager.Instance.LoadRules ? "green" : "red")}>{RulesManager.Instance.LoadRules}</color>");
                    break;
                case "force-crash":
                    bool isCritical = false;
                    if (args.Length > 1 && args[1].ToLower() == "critical")
                    {
                        isCritical = true;
                    }
                    ExceptionManager.New(new System.Exception("Test exception"), isCritical, "Test exception: " + System.Guid.NewGuid());
                    break;
                case "resolution":
                    try
                    {
                        int width = int.Parse(args[1]);
                        int height = int.Parse(args[2]);

                        Screen.SetResolution(width, height, false);
                    }
                    catch
                    {
                        ModConsole.LogError("Failed setting resolution.");
                    }
                    break;
                case "quality-settings":
                    try
                    {
                        QualitySettings.SetQualityLevel(int.Parse(args[1]), true);
                    }
                    catch
                    {
                        ModConsole.LogError("Failed setting quality settings.");
                    }
                    break;
            }
        }

19 Source : LightModel.cs
with MIT License
from Avanade

public LightViewModel<U> MapTo<U>() where U : LightViewModel<U>, ILightViewModel, new()
        {
            U viewModel = new U();

            ///By reflection, browse viewModel by identifying all attributes and lists for validation.  
            foreach (FieldInfo fieldInfo in this.GetType().GetFields())
            {
                dynamic value = fieldInfo.GetValue(this);
                if (value != null)
                {
                    FieldInfo field = this.GetFieldByNameAndType(viewModel, fieldInfo.Name, fieldInfo.FieldType.Name);
                    if (field != null)
                        field.SetValue(viewModel, value);
                }
            }

            foreach (PropertyInfo fieldInfo in this.GetType().GetProperties())
            {
                dynamic value = fieldInfo.GetValue(this);
                if (value != null)
                {
                    PropertyInfo field = this.GetPropertyByNameAndType(viewModel, fieldInfo.Name, fieldInfo.PropertyType.Name);
                    if (field != null)
                        field.SetValue(viewModel, value);
                }
            }
            return viewModel;
        }

See More Examples