[英]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. 在我的C#程序中,我想通过反射将项目添加到
HashSet<T>
。 With a List<T>
this is not a problem because I can cast the list to the non-generic IList
interface: 使用
List<T>
这不是问题,因为我可以将列表IList
转换为非通用IList
接口:
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. 现在,我想对
HashSet<T>
做同样的事情,但是没有像IList
这样的非通用协定可以将其IList
转换并调用Add
方法。 Is there any other way to do it? 还有其他方法吗?
Since you already are using reflection, why not try to lookup the Add method? 由于您已经在使用反射,为什么不尝试查找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)
Maybe add more validations and what not.. :) 也许添加更多的验证,而不是.. :)
You could solve this with dynamic
. 您可以使用
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.