列表与LT;对象>带索引的字符串 [英] List<object> with indexed String
问题描述
通常我们会尝试返回List< object>的对象以及如下例所示的整数索引:
public List< object> data = new List< object>();
public object 测试( int index)
{
return data [index];
}
但我想做的是,我想将索引整数替换为索引字符串,如下所示:
< pre lang =c#> public List< object> data = new List< object>();
public object 测试( string indexName)
{
return data [indexName];
}
void main()
{
....
((ClassA)测试[ AttributeNo1])。Hello1();
((ClassA)测试[ AttributeNo1])。Hello2( blabla);
((ClassA)测试[ AttributeNo1])= new ClassA();
...
((ClassA)数据[ AttributeNo1]) .Hello1();
((ClassA)数据[ AttributeNo1])。Hello2( blabla);
((ClassA)数据[ AttributeNo1])= new ClassA();
...
}
有没有可能这样做?或类似于它的东西,就像MySQL DataReader一样,看起来就像:
DataReader阅读器....
返回阅读器[ AttributeNo1];
使用字典 [ ^ ]:
public 字典<字符串,对象> data = new 字典< string,object>
public object 测试( string indexName)
{
return data [indexName];
}
使用系统;
使用 System.Collections.Generic;
class 计划
{
静态 void Main()
{
Dictionary< string,int> dictionary =
new Dictionary< string,int>();
dictionary.Add( apple, 1 跨度>);
dictionary.Add( windows, 5 跨度>);
// 查看Dictionary是否包含此字符串。
< span class =code-keyword> if (dictionary.ContainsKey( apple ))
{
int value =字典[ apple];
Console.WriteLine( value );
}
// 查看它是否包含此字符串。
if (!dictionary.ContainsKey( 橡子))
{
Console.WriteLine( false );
}
}
}
输出
1
错误
资料来源: http:// www .dotnetperls.com / dictionary [ ^ ]
usually WE try to return the object of the List<object> along with the integer index like example below:
public List<object> data = new List<object>();
public object Test(int index)
{
return data[index];
}
But I would like to do is, I wanting to replace the indexed integer to indexed string like below:
public List<object> data = new List<object>();
public object Test(string indexName)
{
return data[indexName];
}
void main()
{
....
((ClassA)Test["AttributeNo1"]).Hello1();
((ClassA)Test["AttributeNo1"]).Hello2("blabla");
((ClassA)Test["AttributeNo1"]) = new ClassA();
...
((ClassA)data["AttributeNo1"]).Hello1();
((ClassA)data["AttributeNo1"]).Hello2("blabla");
((ClassA)data["AttributeNo1"]) = new ClassA();
...
}
Is there anyway possible to make so? Or something similiar with it, just like MySQL DataReader way, that appears just like:
DataReader reader ....
return reader["AttributeNo1"];
Use Dictionary[^]:
public Dictionary<string,object> data = new Dictionary<string,object> public object Test(string indexName) { return data[indexName]; }
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("apple", 1); dictionary.Add("windows", 5); // See whether Dictionary contains this string. if (dictionary.ContainsKey("apple")) { int value = dictionary["apple"]; Console.WriteLine(value); } // See whether it contains this string. if (!dictionary.ContainsKey("acorn")) { Console.WriteLine(false); } } } Output 1 False
Source: http://www.dotnetperls.com/dictionary[^]
这篇关于列表与LT;对象>带索引的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!