无法将索引应用于“T”类型的表达式
我已经创建了一个通用的方法
public void BindRecordSet(IEnumerable coll1, string propertyName) where T : class
在我的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];
string result= secFTSResult[propertyName];
我收到错误无法将索引应用于’T’类型的表达式
请帮忙谢谢
除非你对声明索引器的接口使用generics约束,否则确实 – 对于abitrary T
不存在。 考虑添加:
public interface IHasBasicIndexer { object this[string propertyName] {get;set;} }
和:
public void BindRecordSet(IEnumerable 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
解析一次)