System.Type.GetProperties()

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

2825 Examples 7

19 Source : AopJsonParser.cs
with Apache License 2.0
from alipay

private static Dictionary<string, AopAttribute> GetAopAttributes(Type type)
        {
            Dictionary<string, AopAttribute> tas = null;
            bool inc = attrs.TryGetValue(type.FullName, out tas);

            if (inc && tas != null) // 从缓存中获取类属性元数据
            {
                return tas;
            }
            else // 创建新的类属性元数据缓存
            {
                tas = new Dictionary<string, AopAttribute>();
            }

            PropertyInfo[] pis = type.GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                AopAttribute ta = new AopAttribute();
                ta.Method = pi.GetSetMethod();

                // 获取对象属性名称
                XmlElementAttribute[] xeas = pi.GetCustomAttributes(typeof(XmlElementAttribute), true) as XmlElementAttribute[];
                if (xeas != null && xeas.Length > 0)
                {
                    ta.ItemName = xeas[0].ElementName;
                }

                // 获取列表属性名称
                if (ta.ItemName == null)
                {
                    XmlArrayItemAttribute[] xaias = pi.GetCustomAttributes(typeof(XmlArrayItemAttribute), true) as XmlArrayItemAttribute[];
                    if (xaias != null && xaias.Length > 0)
                    {
                        ta.ItemName = xaias[0].ElementName;
                    }
                    XmlArrayAttribute[] xaas = pi.GetCustomAttributes(typeof(XmlArrayAttribute), true) as XmlArrayAttribute[];
                    if (xaas != null && xaas.Length > 0)
                    {
                        ta.ListName = xaas[0].ElementName;
                    }
                    if (ta.ListName == null)
                    {
                        continue;
                    }
                }

                // 获取属性类型
                if (pi.PropertyType.IsGenericType)
                {
                    Type[] types = pi.PropertyType.GetGenericArguments();
                    ta.ListType = types[0];
                }
                else
                {
                    ta.ItemType = pi.PropertyType;
                }

                tas.Add(pi.Name + ta.ItemType + ta.ListType, ta);
            }

            attrs[type.FullName] = tas;
            return tas;
        }

19 Source : StringUtil.cs
with Apache License 2.0
from alipay

public static string ToString(object obj)
        {
            if (obj == null)
            {
                return "null";
            }

            Type type = obj.GetType();
            if (string.Equals("System", type.Namespace))
            {
                return "\"" + obj.ToString() + "\"";
            }

            // clreplaced
            string result = "{";

            PropertyInfo[] pis = type.GetProperties();
            for (int i = 0; i < pis.Length; i++)
            {

                PropertyInfo pi = pis[i];
                Type pType = pi.PropertyType;

                MethodInfo getMethod = pi.GetGetMethod();
                object value = getMethod.Invoke(obj, null);
                if (value == null)
                {
                    continue;
                }

                string valueString = "";

                if (string.Equals("System", pType.Namespace))
                {
                    valueString = "\"" + value.ToString() + "\"";
                }
                else if (string.Equals("System.Collections.Generic", pType.Namespace))
                {
                    valueString = List2String(value);
                }
                else
                {
                    valueString = ToString(value);
                }

                if (i != 0)
                {
                    result += ",";
                }
                result += "\"" + pi.Name + "\":" + valueString + "";
            }
            result += "}";

            return result;
        }

19 Source : GridifyMapper.cs
with MIT License
from alirezanet

public IGridifyMapper<T> GenerateMappings()
      {
         foreach (var item in typeof(T).GetProperties())
         {
            // skip clreplacedes
            if (item.PropertyType.IsClreplaced && item.PropertyType != typeof(string))
               continue;

            var name = char.ToLowerInvariant(item.Name[0]) + item.Name.Substring(1); // camel-case name
            _mappings.Add(new GMap<T>(name, CreateExpression(item.Name)!));
         }

         return this;
      }

19 Source : GridifyMapperShould.cs
with MIT License
from alirezanet

[Fact]
      public void GenerateMappings()
      {
         _sut.GenerateMappings();
         
         var props = typeof(TestClreplaced).GetProperties()
            .Where(q => !q.PropertyType.IsClreplaced || q.PropertyType == typeof(string)); 

         replacedert.Equal(props.Count(), _sut.GetCurrentMaps().Count());
         replacedert.True(_sut.HasMap("Id"));
      }

19 Source : ObjectExtensions.cs
with MIT License
from alirizaadiyahsi

public static string ToQueryString(this object obj)
        {
            var properties = from p in obj.GetType().GetProperties()
                             where p.GetValue(obj, null) != null
                             select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString());

            return string.Join("&", properties.ToArray());
        }

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 : ConsoleApp.cs
with MIT License
from allisterb

internal static void SetPropFromDict(Type t, object o, Dictionary<string, object> p)
        {
            foreach (PropertyInfo prop in t.GetProperties())
            {
                if (p.ContainsKey(prop.Name) && prop.PropertyType == p[prop.Name].GetType())
                {
                    prop.SetValue(o, p[prop.Name]);
                }
            }
        }

19 Source : Stage.cs
with MIT License
from allisterb

protected static void SetPropFromDict(Type t, object o, Dictionary<string, object> p)
        {
            foreach (PropertyInfo prop in t.GetProperties())
            {
                if (p.ContainsKey(prop.Name) && prop.PropertyType == p[prop.Name].GetType())
                {
                    prop.SetValue(o, p[prop.Name]);
                }
            }
        }

19 Source : StringHelper.cs
with MIT License
from alonsoalon

public static string Format(string str, object obj)
        {
            if (str.IsNull())
            {
                return str;
            }
            string s = str;
            if (obj.GetType().Name == "JObject")
            {
                foreach (var item in (Newtonsoft.Json.Linq.JObject)obj)
                {
                    var k = item.Key.ToString();
                    var v = item.Value.ToString();
                    s = Regex.Replace(s, "\\{" + k + "\\}", v, RegexOptions.IgnoreCase);
                }
            }
            else
            {
                foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())
                {
                    var xx = p.Name;
                    var yy = p.GetValue(obj).ToString();
                    s = Regex.Replace(s, "\\{" + xx + "\\}", yy, RegexOptions.IgnoreCase);
                }
            }
            return s;
        }

19 Source : DeepCopy.cs
with MIT License
from alonsoalon

public static void CopyToAll<T>(this object source, T target) where T : clreplaced
        {
            if (source == null)
            {
                return;
            }

            if (target == null)
            {
                throw new ApplicationException("target 未实例化!");
            }

            var properties = target.GetType().GetProperties();
            foreach (var targetPro in properties)
            {
                try
                {
                   
                    var propertyValue = source.GetType().GetProperty(targetPro.Name).GetValue(source, null);
                    if (propertyValue != null)
                    {
                        if (propertyValue.GetType().IsEnum)
                        {
                            continue;
                        }

                        target.GetType().InvokeMember(targetPro.Name, BindingFlags.SetProperty, null, target, new object[] { propertyValue });
                    }

                    
                }
                catch (Exception ex)
                {
                    string strErr = ex.ToString();
                }
            }

        }

19 Source : BaseClone.cs
with MIT License
from alonsoalon

public static object CloneObject(object o)
        {
            Type t = o.GetType();
            PropertyInfo[] properties = t.GetProperties();
            Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);
            foreach (PropertyInfo pi in properties)
            {
                if (pi.CanWrite)
                {
                    object value = pi.GetValue(o, null);
                    pi.SetValue(p, value, null);
                }
            }
            return p;
        }

19 Source : Schema.cs
with MIT License
from Aminator

public bool IsEmpty()
        {
            return this.GetType().GetProperties().All(property => Object.Equals(property.GetValue(this), property.GetValue(empty)));
        }

19 Source : Connection.cs
with MIT License
from amolines

private IEnumerable<PropertyInfo> Properties()
        {
            return GetType().GetProperties().Where(p => CustomAttributeExtensions.GetCustomAttributes<ConnectionAttribute>((MemberInfo) p).Any()).ToArray();
        }

19 Source : ObjectInfo.cs
with MIT License
from amolines

public PropertyInfo[] GetProperties(Type type)
        {
            return type.GetProperties();
        }

19 Source : Message.cs
with MIT License
from amolines

private IEnumerable<PropertyInfo> Properties()
        {
            return GetType().GetProperties().Where(p => !CustomAttributeExtensions.GetCustomAttributes<InternalPropertyAttribute>((MemberInfo) p).Any()).ToArray();
        }

19 Source : Snapshot.cs
with MIT License
from amolines

private IEnumerable<PropertyInfo> Properties()
        {
            return GetType().GetProperties().Where(p => !p.GetCustomAttributes<InternalPropertyAttribute>().Any()).ToArray();
        }

19 Source : FieldAttribute.cs
with MIT License
from amolines

public static  Dictionary<string, Type> GetFields<T>(bool onlyFullTextSearch = false)
        {
            var fields = GetFields(typeof(T), k=>k.Name, onlyFullTextSearch);
            var deepFields = typeof(T).GetProperties<DeepFieldAttribute>();
            foreach (var deepField in deepFields)
            {
                var name = deepField.GetCustomAttribute<DeepFieldAttribute>().Name;
                fields.TryAddRange(GetFields(name, deepField.PropertyType, onlyFullTextSearch));
            }
            return fields;
        }

19 Source : FieldAttribute.cs
with MIT License
from amolines

private static Dictionary<string, Type> GetFields(Type type, Func<FieldAttribute, string> keySelector, bool onlyFullTextSearch)
        {
            Dictionary<string, Type> fields;
            if (onlyFullTextSearch)
            {
                fields = type.GetProperties<FieldAttribute>(k => k.FullTextSearch)
                    .ToDictionary(k => keySelector(k.GetCustomAttribute<FieldAttribute>()), v => v.PropertyType);
            }
            else
            {
                fields = type.GetProperties<FieldAttribute>()
                    .ToDictionary(k => keySelector(k.GetCustomAttribute<FieldAttribute>()), v => v.PropertyType);
            }

            return fields;
        }

19 Source : FieldAttribute.cs
with MIT License
from amolines

private static Dictionary<string, Type> GetFields(string name, Type type, bool onlyFullTextSearch = false)
        {
            var fields = GetFields(type , k => $"{name}.{k.Name}", onlyFullTextSearch);
            var deepFields = type.GetProperties<DeepFieldAttribute>();
            foreach (var deepField in deepFields)
            {
                var newName = $"{name}.{deepField.GetCustomAttribute<DeepFieldAttribute>().Name}";
                fields.TryAddRange(GetFields(newName, deepField.ReflectedType));
            }

            return fields;
        }

19 Source : TypeExtensions.cs
with MIT License
from amolines

public static IEnumerable<PropertyInfo> GetProperties<T>(this Type type)
            where T : Attribute
        {
            return type
                .GetProperties()
                .Where(p => CustomAttributeExtensions.GetCustomAttributes<T>((MemberInfo)p).Any());
        }

19 Source : TypeExtensions.cs
with MIT License
from amolines

public static IEnumerable<PropertyInfo> GetProperties<T>(this Type type, Func<T, bool> predicate)
            where T : Attribute
        {
            return type.GetProperties<T>()
                .Where(p=> predicate(p.GetCustomAttribute<T>()));
        }

19 Source : Header.cs
with MIT License
from amolines

private IEnumerable<PropertyInfo> Properties()
        {
            return GetType().GetProperties().Where(p => CustomAttributeExtensions.GetCustomAttributes<HeaderNameAttribute>((MemberInfo)p).Any());
        }

19 Source : TypeExtensions.cs
with Apache License 2.0
from AndcultureCode

public static bool HasPublicProperty(this Type type, string propertyName) =>
            type.GetProperties().Any(property => property.Name == propertyName);

19 Source : DataTable.cs
with GNU General Public License v3.0
from AndreiFedarets

private static DataTableColumn[] ExtractDataColumns()
        {
            List<DataTableColumn> columns = new List<DataTableColumn>();
            PropertyInfo[] properties = typeof(T).GetProperties();
            foreach (PropertyInfo property in properties)
            {
                DataTableColumnAttribute attribute = property.GetCustomAttribute<DataTableColumnAttribute>();
                if (attribute != null)
                {
                    DataTableColumn column = new DataTableColumn(attribute, property);
                    columns.Add(column);
                }
            }
            return columns.ToArray();
        }

19 Source : PropertyBag.cs
with MIT License
from andyalm

private void ReflectObject(object obj)
        {
            foreach (var property in obj.GetType().GetTypeInfo().GetProperties())
            {
                _properties[property.Name] = property.GetValue(obj);
            }
        }

19 Source : CsvInputFormatter.cs
with GNU General Public License v3.0
from andysal

private object readStream(Type type, Stream stream)
        {
            // We only proocess an IList item at present and simple model type with properties
            IList list = (IList)Activator.CreateInstance(type);

            var reader = new StreamReader(stream);

            bool skipFirstLine = true;
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(';');
                if (skipFirstLine)
                {
                    skipFirstLine = false;
                }
                else
                {
                    var itemTypeInGeneric = list.GetType().GetType().GenericTypeArguments[0];
                    var item = Activator.CreateInstance(itemTypeInGeneric);
                    var properties = item.GetType().GetProperties();
                    for (int i = 0; i < values.Length; i++)
                    {
                        properties[i].SetValue(item, Convert.ChangeType(values[i], properties[i].PropertyType), null);
                    }

                    list.Add(item);
                }

            }

            return list;
        }

19 Source : CsvOutputFormatter.cs
with GNU General Public License v3.0
from andysal

private void writeStream(Type type, object value, Stream stream)
        {
            Type itemType = type.GetGenericArguments()[0];

            StringWriter _stringWriter = new StringWriter();

            _stringWriter.WriteLine(
                string.Join<string>(
                    ";", itemType.GetProperties().Select(x => x.Name)
                )
            );

            foreach (var obj in (IEnumerable<object>)value)
            {

                var vals = obj.GetType().GetProperties().Select(
                    pi => new {
                        Value = pi.GetValue(obj, null)
                    }
                );

                string _valueLine = string.Empty;

                foreach (var val in vals)
                {

                    if (val.Value != null)
                    {

                        var _val = val.Value.ToString();

                        //Check if the value contans a comma and place it in quotes if so
                        if (_val.Contains(","))
                            _val = string.Concat("\"", _val, "\"");

                        //Replace any \r or \n special characters from a new line with a space
                        if (_val.Contains("\r"))
                            _val = _val.Replace("\r", " ");
                        if (_val.Contains("\n"))
                            _val = _val.Replace("\n", " ");

                        _valueLine = string.Concat(_valueLine, _val, ";");

                    }
                    else
                    {

                        _valueLine = string.Concat(string.Empty, ";");
                    }
                }

                _stringWriter.WriteLine(_valueLine.TrimEnd(';'));
            }

            var streamWriter = new StreamWriter(stream);
            streamWriter.Write(_stringWriter.ToString());
            streamWriter.Flush();
        }

19 Source : Sql.cs
with MIT License
from anet-team

public static string[] GetParamNames(object param)
        {
            if (param == null)
            {
                return new string[] { };
            }

            if (param is string str)
            {
                if (str.Contains(','))
                    return str
                        .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => x.Trim()).ToArray();
                return new[] { str };
            }

            if (param is IEnumerable<string> array)
            {
                return array.ToArray();
            }

            if (param is DynamicParameters dynamicParameters)
            {
                return dynamicParameters.ParameterNames.ToArray();
            }

            var type = param is Type ? (param as Type) : param.GetType();

            return type
                .GetProperties()
                .Where(x => x.PropertyType.IsSimpleType() || x.PropertyType.GetAnyElementType().IsSimpleType())
                .Select(x => x.Name).ToArray();
        }

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

public static void CopyTo<T>(this object source, T target) where T : clreplaced, new()
        {
            if (source == null)
                return;

            if (target == null)
            {
                target = new T();
            }

            foreach (var property in target.GetType().GetProperties())
            {
                // 这里可以判断一下当前属性值是否为空的 source.GetType().GetProperty(property.Name).GetValue(source, null)
                target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new object[] { source.GetType().GetProperty(property.Name).GetValue(source, null) });
            }
        }

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

public static void RemoveSpecialPropertyValue(this object source)
        {
            var properties = source.GetType().GetProperties();
            foreach (var x in properties)
            {
                if (x.GetAccessors().Any(y => y.IsVirtual))
                {
                    source.GetType().GetProperty(x.Name).SetValue(source, null, null);
                }
            }
        }

19 Source : JsonMapper.cs
with MIT License
from AnotherEnd15

private static void AddArrayMetadata(Type type)
        {
            if (array_metadata.ContainsKey(type))
                return;

            ArrayMetadata data = new ArrayMetadata();

            data.IsArray = type.IsArray;

            if (type.GetInterface("System.Collections.IList") != null)
                data.IsList = true;

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

                ParameterInfo[] parameters = p_info.GetIndexParameters();

                if (parameters.Length != 1)
                    continue;

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

            lock (array_metadata_lock)
            {
                try
                {
                    array_metadata.Add(type, data);
                }
                catch (ArgumentException)
                {
                    return;
                }
            }
        }

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 : Settings.Defaults.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public void Reset()
        {
            lock (this.locker)
            {
                var pis = this.GetType().GetProperties();
                foreach (var pi in pis)
                {
                    try
                    {
                        var defaultValue =
                            DefaultValues.ContainsKey(pi.Name) ?
                            DefaultValues[pi.Name] :
                            null;

                        if (defaultValue != null)
                        {
                            pi.SetValue(this, defaultValue);
                        }
                    }
                    catch
                    {
                        Debug.WriteLine($"Settings Reset Error: {pi.Name}");
                    }
                }
            }
        }

19 Source : EnmityModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public void RaiseAllPropertiesChanged()
        {
            foreach (var pi in this.GetType().GetProperties())
            {
                this.RaisePropertyChanged(pi.Name);
            }
        }

19 Source : Settings.Defaults.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public void Reset()
        {
            lock (locker)
            {
                var pis = this.GetType().GetProperties();
                foreach (var pi in pis)
                {
                    try
                    {
                        var defaultValue =
                            DefaultValues.ContainsKey(pi.Name) ?
                            DefaultValues[pi.Name] :
                            null;

                        if (defaultValue != null)
                        {
                            pi.SetValue(this, defaultValue);
                        }
                    }
                    catch
                    {
                        Debug.WriteLine($"Settings Reset Error: {pi.Name}");
                    }
                }
            }
        }

19 Source : MobListModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public void RaiseAllPropertiesChanged()
        {
            foreach (var pi in this.GetType().GetProperties())
            {
                this.RaisePropertyChanged(pi.Name);
            }

            foreach (var mob in this.MobList)
            {
                mob.RaiseAllPropertiesChanged();
            }
        }

19 Source : ColorDialogViewModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private PredefinedColor[] EnumlatePredefinedColors()
        {
            var list = new List<PredefinedColor>();

            var t1 = Task.Run(() =>
            {
                var solidColors = new List<PredefinedColor>();
                foreach (var color in typeof(Colors).GetProperties())
                {
                    try
                    {
                        solidColors.Add(new PredefinedColor()
                        {
                            Name = color.Name,
                            Color = (Color)ColorConverter.ConvertFromString(color.Name)
                        });
                    }
                    catch
                    {
                    }
                }

                return solidColors.OrderBy(x => x.Color.ToString());
            });

            var t2 = Task.Run(() =>
            {
                var waColors = new List<PredefinedColor>();
                foreach (var color in typeof(WaColors).GetProperties())
                {
                    try
                    {
                        waColors.Add(new PredefinedColor()
                        {
                            Name = color.Name,
                            Color = (Color)color.GetValue(null, null),
                        });
                    }
                    catch
                    {
                    }
                }

                return waColors.OrderBy(x => x.Color.ToString());
            });

            list.AddRange(t1.Result);
            list.AddRange(t2.Result);

            return list.ToArray();
        }

19 Source : ObjectExtensions.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private static IList<PropertyMap> GetMatchingProperties(Type sourceType, Type targetType)
        {
            var sourceProperties = sourceType.GetProperties();
            var targetProperties = targetType.GetProperties();

            var properties = (
                from s in sourceProperties
                from t in targetProperties
                where
                s.Name == t.Name &&
                s.CanRead &&
                t.CanWrite &&
                s.PropertyType.IsPublic &&
                t.PropertyType.IsPublic &&
                s.PropertyType == t.PropertyType &&
                (
                    (s.PropertyType.IsValueType && t.PropertyType.IsValueType) ||
                    (s.PropertyType == typeof(string) && t.PropertyType == typeof(string))
                )
                select new PropertyMap
                {
                    SourceProperty = s,
                    TargetProperty = t
                }).ToList();

            return properties;
        }

19 Source : ObjectExtensions.cs
with MIT License
from anoyetta

public static void CopyProperties(
            this object source,
            object destination,
            params string[] ignoreProperties)
        {
            var pis = source.GetType().GetProperties();
            foreach (var pi in pis)
            {
                if (ignoreProperties != null)
                {
                    if (ignoreProperties.Contains(pi.Name))
                    {
                        continue;
                    }
                }

                var value = pi.GetValue(
                    source);

                if (value != null)
                {
                    pi.SetValue(destination, value);
                }
            }
        }

19 Source : JsonConfigBase.cs
with MIT License
from anoyetta

public void LoadDefaultValues()
        {
            if (!DefaultValues.ContainsKey(DebugModeDefaultValue.Key))
            {
                DefaultValues.Add(DebugModeDefaultValue.Key, DebugModeDefaultValue.Value);
            }

            var pis = this.GetType().GetProperties();
            foreach (var pi in pis)
            {
                try
                {
                    var defaultValue =
                        DefaultValues.ContainsKey(pi.Name) ?
                        DefaultValues[pi.Name] :
                        null;

                    if (defaultValue != null)
                    {
                        pi.SetValue(this, defaultValue);
                    }
                }
                catch
                {
                    Debug.WriteLine($"Error! Config load default values : {pi.Name}");
                }
            }
        }

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

static string PrintProperties(object o)
        {
            var sb = new StringBuilder("(");
            var fields = o.GetType().GetProperties();
            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 : NetCoreForceModelGeneratorNamingConvention.cs
with MIT License
from anthonyreilly

public IEnumerable<string> GetAllPropertyNames(Type elementType)
        {
            var allPropertyNames = (
                    from property in elementType.GetTypeInfo().GetProperties() 
                    let type = property.PropertyType 
                    where type == typeof(string) || type == typeof(decimal?) || type == typeof(DateTime?) 
                    where !IgnoreProperty(property)
                    select GetPropertyName(property))
                .ToList();
            return allPropertyNames;
        }

19 Source : RealBinaryMapping.Read.cs
with Apache License 2.0
from AntonioDePau

private object ReadRawObject(BinaryReader reader, object item, int baseOffset)
        {
            if (mappings.TryGetValue(item.GetType(), out var mapping))
            {
                return mapping.Reader(new MappingReadArgs
                {
                    Reader = reader,
                    DataAttribute = new DataAttribute()
                });
            }

            var properties = item.GetType()
                .GetProperties()
                .Select(x => GetPropertySettings(item.GetType(), x))
                .Where(x => x.DataInfo != null)
                .ToList();

            var args = new MappingReadArgs
            {
                Reader = reader
            };

            foreach (var property in properties)
            {
                if (property.DataInfo.Offset.HasValue)
                {
                    var newPosition = baseOffset + property.DataInfo.Offset.Value;
                    if (reader.BaseStream.Position != newPosition + 1)
                        args.BitIndex = 0;

                    reader.BaseStream.Position = newPosition;
                }

                args.Count = property.GetLengthFunc?.Invoke(item) ?? property.DataInfo.Count;
                var value = ReadProperty(args, property.MemberInfo.PropertyType, property);
                property.MemberInfo.SetValue(item, value, BindingFlags.Default, null, null, null);
            }

            args.BitIndex = 0;
            return item;
        }

19 Source : RealBinaryMapping.Write.cs
with Apache License 2.0
from AntonioDePau

private object WriteObject(MappingWriteArgs args, object item, int baseOffset)
        {
            if (mappings.TryGetValue(item.GetType(), out var mapping))
            {
                mapping.Writer(new MappingWriteArgs
                {
                    Writer = args.Writer,
                    Item = item,
                    DataAttribute = new DataAttribute(),
                });

                return item;
            }

            var properties = item.GetType()
                .GetProperties()
                .Select(x => GetPropertySettings(item.GetType(), x))
                .Where(x => x.DataInfo != null)
                .ToList();

            foreach (var property in properties)
            {
                if (property.DataInfo.Offset.HasValue)
                {
                    var newPosition = baseOffset + property.DataInfo.Offset.Value;
                    if (args.Writer.BaseStream.Position != newPosition)
                        FlushBitField(args);

                    args.Writer.BaseStream.Position = newPosition;
                }

                var value = property.MemberInfo.GetValue(item, BindingFlags.Default, null, null, null);
                args.Count = property.GetLengthFunc?.Invoke(item) ?? property.DataInfo.Count;
                WriteProperty(args, value, property.MemberInfo.PropertyType, property);
            }

            FlushBitField(args);
            return item;
        }

19 Source : FuzzyLogicCore.cs
with MIT License
from antonio-leonardo

private IEnumerable<string> GetPropertiesNames()
        {
            PropertyInfo[] props = this.TypeOf.GetProperties();
            for (int i = 0; i < props.Length; i++)
            {
                yield return props[i].Name;
            }
        }

19 Source : DataAccessLayer.cs
with MIT License
from AntonyCorbett

private static List<string> GetColumnNames<TRowType>()
        {
            var properties = typeof(TRowType).GetProperties();
            return properties.Select(property => property.Name).ToList();
        }

19 Source : Widget.cs
with GNU General Public License v3.0
from AnyStatus

public virtual object Clone()
        {
            var clone = (Widget)Activator.CreateInstance(GetType());

            var properties = GetType()
                .GetProperties()
                .Where(p => p.CanWrite && p.Name != nameof(Id) && p.Name != nameof(Parent) && p.Name != "Item")
                .ToList();

            properties.ForEach(p => p.SetValue(clone, p.GetValue(this, null), null));

            clone.Id = Guid.NewGuid().ToString();

            if (HasChildren)
            {
                foreach (var child in this)
                {
                    clone.Add((IWidget)child.Clone());
                }
            }

            return clone;
        }

19 Source : PropertyViewModelBuilder.cs
with GNU General Public License v3.0
from AnyStatus

private static IEnumerable<PropertyInfo> GetProperties(object source) => source.GetType().GetProperties().Where(p => p.CanWrite && p.IsBrowsable()).OrderBy(p => p.Order());

19 Source : DatabaseOperation.cs
with MIT License
from ap0405140

public List<T> Query<T>(string sTsql, bool closeconnect = true)
        {
            DataTable dt;
            List<T> ls;
            T tt;
            object tt2;
            PropertyInfo[] props;
            FieldInfo fieldinfo;
            DataColumn[] dtcolumns;
            ColumnAttribute[] columnattributes;
            string targettype, columnname;
            int i;

            try
            {
                dt = Query(sTsql, closeconnect);
                dtcolumns = dt.Columns.Cast<DataColumn>().ToArray();
                ls = new List<T>();

                targettype = "";
                if (typeof(T).IsValueType 
                    || typeof(T).Name.ToLower().Contains("string"))
                {
                    targettype = "ValueType";
                }
                if (typeof(T).Name.StartsWith("ValueTuple"))
                {
                    targettype = "ValueTuple";
                }
                if (typeof(T).GetConstructors().Any(p => p.GetParameters().Length == 0))
                {
                    targettype = "Clreplaced";
                }

                foreach (DataRow dr in dt.Rows)
                {
                    switch (targettype)
                    {
                        case "ValueType":
                            tt = (dr[0] == DBNull.Value ? default(T) : (T)dr[0]);
                            ls.Add(tt);
                            break;
                        case "ValueTuple":
                            tt = Activator.CreateInstance<T>();
                            tt2 = tt;
                            for (i = 0; i <= dtcolumns.Length - 1; i++)
                            {
                                fieldinfo = tt2.GetType().GetField("Item" + (i + 1).ToString());
                                if (fieldinfo != null)
                                {
                                    fieldinfo.SetValue(tt2, (dr[i] == DBNull.Value ? null : dr[i].ToSpecifiedType(fieldinfo.FieldType)));
                                }
                            }
                            tt = (T)tt2;
                            ls.Add(tt);
                            break;
                        case "Clreplaced":
                            tt = (T)Activator.CreateInstance(typeof(T));
                            props = typeof(T).GetProperties();
                            foreach (PropertyInfo prop in props)
                            {
                                columnattributes = prop.GetCustomAttributes(typeof(ColumnAttribute), false).Cast<ColumnAttribute>().ToArray();
                                columnname = (columnattributes.Length > 0 && string.IsNullOrEmpty(columnattributes[0].Name) == false
                                                ?
                                                   columnattributes[0].Name
                                                :
                                                   prop.Name);
                                if (dtcolumns.Any(c => c.ColumnName == columnname))
                                {
                                    prop.SetValue(tt, (dr[columnname] == DBNull.Value ? null : dr[columnname]));
                                }
                            }
                            ls.Add(tt);
                            break;
                        default:
                            break;
                    }
                }

                return ls;
            }
            catch (Exception ex)
            {
                throw new Exception("Run SQL: \r\n" + sTsql
                                    + "\r\n\r\n" + "ExceptionSource: " + ex.Source
                                    + "\r\n\r\n" + "ExceptionMessage: " + ex.Message);
            }
            finally
            {
                //if (closeconnect == true)
                //{
                //    if (scn.State == ConnectionState.Open)
                //    {
                //        scn.Close();
                //    }

                //    scn.Dispose();
                //}
            }
        }

See More Examples