我创建了一个像
这样的通用方法
public void BindRecordSet<T>(IEnumerable<T> coll1, string propertyName)
where T : class
public void BindRecordSet<T>(IEnumerable<T> coll1, string propertyName)
where T : class
在我的班级'T'我写了索引器
现在在我的方法中编写像
这样的代码 public object this[string propertyName]
{
get
{
Type t = typeof(SecUserFTSResult);
PropertyInfo pi = t.GetProperty(propertyName);
return pi.GetValue(this, null);
}
set
{
Type t = typeof(SecUserFTSResult);
PropertyInfo pi = t.GetProperty(propertyName);
pi.SetValue(this, value, null);
}
}
var result = ((T[])(coll1.Result))[0];
我收到错误 无法将索引应用于“T”类型的表达式
请帮忙 感谢
答案 0 :(得分:8)
除非您对声明索引器的接口使用泛型约束,否则确实 - abitrary T
不存在。考虑添加:
public interface IHasBasicIndexer { object this[string propertyName] {get;set;} }
和
public void BindRecordSet<T>(IEnumerable<T> coll1, string propertyName)
where T : class, IHasBasicIndexer
和
public class MyClass : IHasBasicIndexer { ... }
(随意将IHasBasicIndexer
重命名为更合理的内容)
或者4.0中更简单的替代方案(但有点hacky IMO):
dynamic secFTSResult = ((T[])(coll1.Result))[0];
string result= secFTSResult[propertyName];
(将在运行时每T
解析一次)