无法将索引应用于“T”类型的表达式

时间:2011-08-22 05:23:21

标签: c#

我创建了一个像

这样的通用方法

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”类型的表达式

请帮忙 感谢

1 个答案:

答案 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解析一次)