Set object property using reflection

后端 未结 10 1470
终归单人心
终归单人心 2020-11-21 23:22

Is there a way in C# where I can use reflection to set an object property?

Ex:

MyObject obj = new MyObject();
obj.Name = \"Value\";

10条回答
  •  粉色の甜心
    2020-11-22 00:02

    You can try this out when you want to mass-assign properties of an Object from another Object using Property names:

    public static void Assign(this object destination, object source)
        {
            if (destination is IEnumerable && source is IEnumerable)
            {
                var dest_enumerator = (destination as IEnumerable).GetEnumerator();
                var src_enumerator = (source as IEnumerable).GetEnumerator();
                while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
                    dest_enumerator.Current.Assign(src_enumerator.Current);
            }
            else
            {
                var destProperties = destination.GetType().GetProperties();
                foreach (var sourceProperty in source.GetType().GetProperties())
                {
                    foreach (var destProperty in destProperties)
                    {
                        if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
                        {
                            destProperty.SetValue(destination,     sourceProperty.GetValue(source, new object[] { }), new object[] { });
                            break;
                }
            }
        }
    }
    

提交回复
热议问题