简体   繁体   中英

Creating a non-generic function for adding items to a HashSet<T>

In my C# program, I want to add items to a HashSet<T> via reflection. With a List<T> this is not a problem because I can cast the list to the non-generic IList interface:

foreach (PropertyInfo property in myClass.GetType().GetProperties())
{
    object value = property.GetValue(myClass);
    IList valueAsIList = value as IList;
    if (valueAsIList != null)
        valueAsIList.Add(item2Insert);
}

Now I want to do the same thing with HashSet<T> but there is no non-generic contract like IList that I could cast it to and call the Add method. Is there any other way to do it?

Since you already are using reflection, why not try to lookup the Add method?

var addMethod = value.GetType().GetMethods().FirstOrDefault(m => m.Name == "Add");

//validate this method; has it been found? What should we do if it didnt? Maybe it should be SingleOrDefault

addMethod.Invoke(value, valueToAdd)

Maybe add more validations and what not.. :)

You could solve this with dynamic . It will "take care of" the reflection work for you.

using System;
using System.Collections.Generic;

namespace Bob
{
    public class Program
    {
        static void Main(string[] args)
        {
            var hash = new HashSet<int>();
            Console.WriteLine(hash.Count);
            Add(hash);
            Console.WriteLine(hash.Count);
            Console.ReadLine();
        }

        private static void Add(dynamic hash)
        {
            hash.Add(1);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM