开发者

setting scalar value on collection using introspection

I am doing something like the answer on: Set object property using reflection

Dynam开发者_JAVA技巧ically setting the value of a object property. I have a function wrapping this sort of functionality and it works great. However, I want to make it so that it looks at the property type to see if it is some sort of collection and add the value/object to the collection.

I tried to do something like: if (object is ICollection) The problem is that VS2010 wants me to type the collection which I dont know how to do programatically.

So what I want to do is something like the following given subject is the target object and value is value to be set:

public void setPropertyOnObject(object subject, string Name, object value)
{
  var property = subject.GetType().GetProperty(Name)
  // -- if property is collection ??
  var collection = property.GetValue(subject, null);
  collection.add(value)
  // -- if propert is not a collection
  property.SetValue(subject, value, null);
}


You can dynamically check a typed collection (and add an item to it) thusly:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Object subject = new HasList();
            Object value = "Woop";
            PropertyInfo property = subject.GetType().GetProperty("MyList", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
            var genericType = typeof (ICollection<>).MakeGenericType(new[] {value.GetType()});
            if (genericType.IsAssignableFrom(property.PropertyType))
                genericType.GetMethod("Add").Invoke(property.GetValue(subject, null), new[] { value });
        }
    }

    internal class HasList
    {
        public List<String> MyList { get; private set; }
        public HasList()
        {
            MyList = new List<string>();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜