【问题标题】:Creating a non-generic function for adding items to a HashSet<T>创建用于将项目添加到 HashSet<T> 的非泛型函数
【发布时间】:2018-01-14 13:51:20
【问题描述】:

在我的 C# 程序中,我想通过反射将项目添加到 HashSet&lt;T&gt;。使用List&lt;T&gt; 这不是问题,因为我可以将列表转换为非通用IList 接口:

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

现在我想对HashSet&lt;T&gt; 做同样的事情,但是没有像IList 这样的非通用合同,我可以将其转换为并调用Add 方法。还有其他方法吗?

【问题讨论】:

  • Hashset&lt;T&gt; 也是 ICollection&lt;T&gt;
  • @stuartd 和 Chris:OP 之所以提到 IList,是因为 List&lt;T&gt; 实现了非泛型 IList 接口,该接口可用于将无类型对象添加到集合中。但是HashSet&lt;T&gt; 没有它实现的这样一个非通用合约。
  • 啊,我没有完全理解这个问题,谢谢你的注意。

标签: c# generics reflection hashset


【解决方案1】:

您可以使用dynamic 解决此问题。它将为您“处理”反射工作。

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);
        }
    }
}

【讨论】:

    【解决方案2】:

    既然您已经在使用反射,为什么不尝试查找 Add 方法?

    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)
    

    也许添加更多验证,什么不...... :)

    【讨论】:

    • 请注意,valueobject,而不是类型,因此您必须使用 value.GetType().GetMethods()…。另外,您可以使用GetMethod(单数)直接获取方法,而无需全部查询。
    • 已修复,谢谢!!关于特定的 GetMethod("Add") 也可以,但是您也必须捕获 AmbiguousMatchException
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    相关资源
    最近更新 更多