【问题标题】:Cannot apply indexing to an expression of type 'T'无法将索引应用于“T”类型的表达式
【发布时间】:2011-08-22 05:23:20
【问题描述】:

我已经创建了一个通用方法,例如

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];

string result= secFTSResult[propertyName];

我收到了错误 无法对“T”类型的表达式应用索引

请帮忙 谢谢

【问题讨论】:

  • 嗨 BoltClock,BindRecordSet 方法是泛型类型方法,这里 T 是 BindRecordSet,其中 Student 是一个类

标签: c#


【解决方案1】:

除非您对声明索引器的接口使用通用约束,否则确实 - 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 解决一次)

【讨论】:

  • 我更喜欢 interface IIndexable&lt;T&gt; { this[T index] { get; set; } } 来匹配 BCL 样式。我很惊讶它还不存在......
  • @Simon 所描述的接口采用string 并返回object - 其中T 在哪里?
  • @MSingh - 我在答案中错过了object;查看更新(对接口定义)
  • 用作where T : class, IIndexable&lt;string&gt;
  • @Simon meh... 使用基于样本 1 的泛型是过度杀伤 IMO。如果它只有一个用例,它就不是“通用的”。
猜你喜欢
  • 1970-01-01
  • 2014-01-09
  • 2018-04-03
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多