fle*_*esh 13 c# generics reflection
这个(缩短的)代码..
for (int i = 0; i < count; i++)
{
object obj = propertyInfo.GetValue(Tcurrent, new object[] { i });
}
Run Code Online (Sandbox Code Playgroud)
..正在抛出'TargetParameterCountException:参数计数不匹配'异常.
'propertyInfo'的基础类型是某些T的集合.'count'是集合中的项目数.我需要遍历集合并对obj执行操作.
建议表示赞赏.
ang*_*son 19
反射一次仅适用于一个级别.
你试图索引该属性,这是错误的.
相反,读取属性的值和您获得的对象,这是您需要索引的对象.
这是一个例子:
using System;
using System.Collections.Generic;
using System.Reflection;
namespace DemoApp
{
public class TestClass
{
public List<Int32> Values { get; private set; }
public TestClass()
{
Values = new List<Int32>();
Values.Add(10);
}
}
class Program
{
static void Main()
{
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;
PropertyInfo pi2 = collection.GetType().GetProperty(indexerName);
Object value = pi2.GetValue(collection, new Object[] { 0 });
Console.Out.WriteLine("tc.Values[0]: " + value);
Console.In.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
29156 次 |
最近记录: |