我正在尝试使用反射获取属性的指定索引的值。
This answer例如,适用于类型为 List<> 的标准属性,但就我而言,我尝试使用的集合具有不同的格式:
public class NumberCollection : List<int>
{
public NumberCollection()
{
nums = new List<int>();
nums.Add(10);
}
public new int this[int i]
{
get { return (int) nums[i]; }
}
private List<int> nums;
}
public class TestClass
{
public NumberCollection Values { get; private set; }
public TestClass()
{
Values = new NumberCollection();
Values.Add(23);
}
}
class Program
{
static void Main(string[] args)
{
TestClass tc = new TestClass();
PropertyInfo pi1 = tc.GetType().GetProperty("Values");
Object collection = pi1.GetValue(tc, null);
// note that there's no checking here that the object really
// is a collection and thus really has the attribute
String indexerName = ((DefaultMemberAttribute)collection.GetType()
.GetCustomAttributes(typeof(DefaultMemberAttribute),
true)[0]).MemberName;
// Code will ERROR on the next line...
PropertyInfo pi2 = collection.GetType().GetProperty(indexerName);
Object value = pi2.GetValue(collection, new Object[] { 0 });
Console.Out.WriteLine("tc.Values[0]: " + value);
Console.In.ReadLine();
}
}
这段代码给出了一个 AmbiguousMatchException(“找到不明确的匹配项。”)。我知道我的收藏类有些做作,但有人可以帮忙吗?
最佳答案
一种选择是使用
var prop = Type.GetProperties()
.Where(prop => prop.DeclaringType == collection.GetType())
.First();
如果需要,将 Collection.GetType()
更改为另一种类型。但基本上:遍历属性而不是使用 Type.GetProperty
。
关于c# - 反射 - 如何在参数的指定索引处获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448433/