设置阵列密钥字符串不是int? [英] Set array key as string not int?

查看:165
本文介绍了设置阵列密钥字符串不是int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想数组键设置像在下面的示例中的字符串,但 C#

 < PHP
$阵列=阵列();
$阵列['KEY_NAME'] =值1;
?>
 

解决方案

你最近在C#中是 词典< TKEY的,TValue>

  VAR字典=新字典<字符串,字符串>();
字典[KEY_NAME] =值1;
 

请注意,词典< TKEY的,TValue> 没有的一样PHP的关联数组,因为它的只有一个类型的密钥访问( TKEY的 - 这是字符串在上面的例子),而不是串/整数键组合(感谢帕维尔澄清了这一点)。

不过,我从来没有听说过一个.NET开发人员抱怨说。


在回应您的评论:

  //在headersSplit元素的数量将是数量':'字符
//符合+ 1。
字符串[] headersSplit = line.Split(:);

串hname = headersSplit [0];

//如果您收​​到一个IndexOutOfRangeException这里,那是因为你
// headersSplit阵列仅具有一个元素。这告诉我,行不
//包含一个':'字符。
串hvalue = headersSplit [1];
 

I am trying to set the array keys as a strings like in the example below, but inC#.

<?php
$array = array();
$array['key_name'] = "value1";
?>

解决方案

The closest you get in C# is Dictionary<TKey, TValue>:

var dict = new Dictionary<string, string>();
dict["key_name"] = "value1";

Note that a Dictionary<TKey, TValue> is not the same as PHP's associative array, because it is only accessible by one type of key (TKey -- which is string in the above example), as opposed to a combination of string/integer keys (thanks to Pavel for clarifying this point).

That said, I've never heard a .NET developer complain about that.


In response to your comment:

// The number of elements in headersSplit will be the number of ':' characters
// in line + 1.
string[] headersSplit = line.Split(':');

string hname = headersSplit[0];

// If you are getting an IndexOutOfRangeException here, it is because your
// headersSplit array has only one element. This tells me that line does not
// contain a ':' character.
string hvalue = headersSplit[1];

这篇关于设置阵列密钥字符串不是int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆