如何构造Lst类,以便我可以通过类的属性引用特定实例?如果在List中不可能在Lst []数组中可能吗?创建/使用/引用此模式中的列表是否具有名称?
我得到的错误是Argument 1: cannot convert from 'string' to 'int'
在Console.WriteLine()中的两个l [" .. List"]
namespace ConsoleApplication1 {
public class Lst {
public string Name;
public Lst(string Name) { this.Name = Name; }
public Lst this[string Name] { get { return this[Name]; } }
}
class Program {
static void Main(string[] args) {
List<Lst> l = new List<Lst>();
l.Add(new Lst("1stList"));
Console.WriteLine("List {0}:", l["1stList"].Name);
Console.WriteLine("List {0}:", l["2ndList"].Name);
Console.ReadKey();
}
}
}
答案 0 :(得分:0)
如何构造Lst类,以便引用特定实例 通过班级的财产?
您可以使用LINQ从列表中获取与条件匹配的项目。例如,获取具有特定名称的项目:
class Program
{
static void Main(string[] args)
{
List<Lst> l = new List<Lst>();
l.Add(new Lst("1stList"));
Console.WriteLine("List {0}:", l.First(item => item.Name == "1stList").Name);
Console.WriteLine("List {0}:", l.First(item => item.Name == "2ndList").Name);
Console.ReadKey();
}
}
public class Lst
{
public string Name;
public Lst(string Name) { this.Name = Name; }
}
答案 1 :(得分:0)
向Weyland Yutani致敬。
msdn.microsoft.com/en-us/library/6x16t2tx.aspx
表达体定义
通常会让索引器立即返回 表达的结果。有一个语法快捷方式来定义它们 使用=&gt;的索引器:C#
public Customer this[long id] => store.LookupCustomer(id);
索引器必须是只读的,并且您不使用get访问器 关键字。
索引器概述
•索引器使对象能够以与数组类似的方式编制索引。
• get 访问者返回一个值。 设置访问者分配值。
•此关键字用于定义索引器。
•value关键字用于定义由...分配的值 设置索引器。
•索引器不必用整数值索引;它起来了 如何定义特定的查找机制。
•索引器可能过载。
•索引器可以有多个形式参数,例如,何时 访问二维数组。
我希望找到语言增长到任何属性可以用作索引器而不必编写我自己的索引器函数。但在那之前我们有Linq。