【问题标题】:C# Indexers must have at least one parameterC# 索引器必须至少有一个参数
【发布时间】:2014-07-22 03:37:00
【问题描述】:

我继承了一些代码,当我尝试运行代码时收到上述错误消息。下面是代码:

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Scripting
{
      [CompilerGenerated]
      [Guid("C7C3F5A0-88A3-11D0-ABCB-00A0C90FFFC0")]    
      [TypeIdentifier]    
      [ComImport]    
      public interface IDrive    
      {   
           [DispId(0)]    
           [IndexerName("Path")]    
           string this[] { [DispId(0)] get; } //The error is here//    

           [DispId(10009)]
           int SerialNumber { [DispId(10009)] get; }

           [DispId(10007)]
           string VolumeName { [DispId(10007)] get; [DispId(10007)] set; }

           [SpecialName]
           [MethodImpl(MethodCodeType = MethodCodeType.Runtime)]
           void _VtblGap1_7();

           [SpecialName]
           [MethodImpl(MethodCodeType = MethodCodeType.Runtime)]
           void _VtblGap2_1();
      }
}

我是 C# 新手,想知道缺少什么参数。

我无法询问原始编码员。任何帮助将不胜感激。

【问题讨论】:

  • 你能指出抛出这个错误的行号吗

标签: c#


【解决方案1】:

正如错误所说,“索引器必须至少有一个参数”。

因此您需要向索引器添加一个参数,例如

string this[int index] { [DispId(0)] get; }

如果你想一想,当你使用索引器时,你提供一个整数作为参数。

例如

string path = myIDrive[0]; // Use the integer parameter to access the element

var wut = myIDrive[?]; // without any parameter, how would you get the Path data?

【讨论】:

    【解决方案2】:
    string this[] { [DispId(0)] get; }
    

    如错误所示,您缺少参数。

    string this[object myIndexerParameter] 
    { 
        get 
        { 
             // return some value based on the parameter passed.  
        }
    }
    

    那你这样称呼它:var something = myIDriveInstance[myIndexValue];

    http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

    这与List<T> 允许传入项目的索引基本相同;因此命名为indexer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多