如题,比如List buf=new List(new string[3]{"a","b","c"});
正常使用下标:string temp=buf[0];得出temp="a".
现在想写一个扩展:string temp=buf["a"];得出temp="a".
当然,举得列子可能不合适,目的是想写一个下标的那种扩展,我记得有这种扩展,但是忘记不知道怎么写的了,望高手指点
不可以,扩展方法不支持索引器。你只能用自定义的类实现:
class MyList : List
{
public string this[string index]
{
return this.First(x => x == index);
}
}
啥玩意,不是说是Java的吗,怎么变成C#了
class MyList : List<string>
{
public string this[string index]
{
return this.First(x => x == index);
}
}
class MyList : List<string>
{
public MyList(IEnumerable<string> x) : base(x) { }
public string this[string index]
{
return this.First(x => x == index);
}
}
调用
MyList buf=new MyList(new string[3]{"a","b","c"});
string s = buf["a"];