建立和使用通用列表?
谁能帮我弄清楚如何在不使用 ArrayList 的情况下简化这段代码?
List<Pair> material = new List<Pair>();
List<string> list = new List<string>();
string tempStr;
int integer = -1;
foreach (string s in ((string)Value).Split(new char[1] { ',' }))
{
if (int.TryParse(s, out integer))
{
tempStr = NameValue.AllKeys[integer];
if (someCondition == true)
{
material.Add(new Pair(tempStr, integer));
}
else
{
list.Add(tempStr);
}
}
}
if(someCondition == true)
{
return material.ExtensionMethodForLists();
}
else
{
return list.ExtensionMethodForLists();
}
当我尝试类似(如下)的操作时,我收到一个错误,因为未初始化隐式类型变量。
var list;
if(someCondition == true)
{
list = new List<Pair>();
}
else
{
list = new List<string>();
}
Can anyone help me figure out how I could simplify this code, without using an ArrayList
?
List<Pair> material = new List<Pair>();
List<string> list = new List<string>();
string tempStr;
int integer = -1;
foreach (string s in ((string)Value).Split(new char[1] { ',' }))
{
if (int.TryParse(s, out integer))
{
tempStr = NameValue.AllKeys[integer];
if (someCondition == true)
{
material.Add(new Pair(tempStr, integer));
}
else
{
list.Add(tempStr);
}
}
}
if(someCondition == true)
{
return material.ExtensionMethodForLists();
}
else
{
return list.ExtensionMethodForLists();
}
When I've tried something like (below) I get an error for not initializing an implicityly-typed variable.
var list;
if(someCondition == true)
{
list = new List<Pair>();
}
else
{
list = new List<string>();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用不同的类型,则需要对变量使用非泛型类型:
或者
就个人而言,我不确定这是一个很好的设计,但它满足要求。
If you are using different types, you would need to use a non-generic type for the variable:
or
Personally, I'm not sure it is a great design, but it satisfies the requirement.
不知道这是否真的简化了,但类似:
Don't know if this actually simplifies, but something like:
如果您要使用
var
,则必须立即分配该值。否则,正如 @Marc 所建议的那样,这是完美的......(好吧,正如他所说 - 满足要求)If you are going to use
var
you must assign the value immediately. Otherwise, as @Marc suggests is perfect... (well, as he says - satisfies the requirement)Python 或其他动态类型语言中会出现类似的情况。不过,如果您使用 .net 4.0,则可以使用dynamic关键字而不是var。
但是,您使用的 C# 是强类型的,而动态关键字实际上是与动态类型语言交互的,如果类型系统妨碍您,您应该重新考虑您的设计。另外,如果您确实需要管理两种类型的集合,那么您应该将其包装在一个类中,并在客户端代码中隐藏这些血淋淋的细节。
Something like that would in Python or some other dynamically typed language. Though if you are using .net 4.0 you could use the dynamic keyword instead of var.
But, you're using C# which is meant to be strongly typed and the dynamic keyword is really meant to interface with dynamically typed languages and if the type system is getting in your way, you should reconsider your design. Also, if you do really need to manage two types of collections like that you should wrap it in a class and hide such gory details from the client code.