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

man*_*der 3 c#

我已经创建了一个通用的方法

public void BindRecordSet<T>(IEnumerable<T> coll1, string propertyName)
            where T : class
Run Code Online (Sandbox Code Playgroud)

var result = ((T[])(coll1.Result))[0];

string result= secFTSResult[propertyName];

我收到错误无法将索引应用于'T'类型的表达式

请帮忙谢谢

Mar*_*ell 8

除非你对声明索引器的接口使用泛型约束,否则确实 - 对于abitrary 不存在T.考虑添加:

public interface IHasBasicIndexer { object this[string propertyName] {get;set;} }
Run Code Online (Sandbox Code Playgroud)

和:

public void BindRecordSet<T>(IEnumerable<T> coll1, string propertyName)
        where T : class, IHasBasicIndexer 
Run Code Online (Sandbox Code Playgroud)

和:

public class MyClass : IHasBasicIndexer { ... }
Run Code Online (Sandbox Code Playgroud)

(随意重命名IHasBasicIndexer为更合理的东西)

或者4.0中更简单的替代方案(但有点hacky IMO):

dynamic secFTSResult = ((T[])(coll1.Result))[0];    
string result= secFTSResult[propertyName];
Run Code Online (Sandbox Code Playgroud)

(将T在运行时解析一次)