从 C# 中的 namevaluecollection 填充对象数组
我是 C# 新手。 这是我正在工作的一个硬编码的东西:
InputProperty grantNumber = new InputProperty();
grantNumber.Name = "udf:Grant Number";
grantNumber.Val = "571-1238";
Update update = new Update();
update.Items = new InputProperty[] { grantNumber };
现在我想概括它以支持 Update 对象中不定数量的项目,我想出了这个,但它无法编译:
Update update = BuildMetaData(nvc); //call function to build Update object
以及函数本身:
private Update BuildMetaData(NameValueCollection nvPairs)
{
Update update = new Update();
InputProperty[] metaData; // declare array of InputProperty objects
int i = 0;
foreach (string key in nvPairs.Keys)
{
metaData[i] = new InputProperty(); // compiler complains on this line
metaData[i].Name = "udf:" + key;
foreach (string value in nvPairs.GetValues(key))
metaData[i].Val = value;
}
update.Items = metaData;
return update; // return the Update object
}
I am new to C#. Here is a hard-coded thing I got working:
InputProperty grantNumber = new InputProperty();
grantNumber.Name = "udf:Grant Number";
grantNumber.Val = "571-1238";
Update update = new Update();
update.Items = new InputProperty[] { grantNumber };
Now I want to generalize this to support an indefinite number of items in the Update object and I came up with this but it fails to compile:
Update update = BuildMetaData(nvc); //call function to build Update object
and the function itself here:
private Update BuildMetaData(NameValueCollection nvPairs)
{
Update update = new Update();
InputProperty[] metaData; // declare array of InputProperty objects
int i = 0;
foreach (string key in nvPairs.Keys)
{
metaData[i] = new InputProperty(); // compiler complains on this line
metaData[i].Name = "udf:" + key;
foreach (string value in nvPairs.GetValues(key))
metaData[i].Val = value;
}
update.Items = metaData;
return update; // return the Update object
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于 Items 集合的大小可能会有所不同,因此您应该使用
List
或Dictionary
等集合类型,而不是数组。Since the size of your Items collection can vary, you should use a collection type like
List<T>
orDictionary<K,V>
instead of an array.对于当前的编译器错误,您需要初始化元数据数组,例如:
使用 linq 您可以:
For the current compiler error, you need to initialize the metaData array, like:
Using linq you could:
如果我没记错的话,您的 InputProperty 数组永远不会初始化。 如果将第 2 行更改为:
这应该可以解决问题。
If I'm not mistaken, your InputProperty array is never initialized. If you change line 2 to this:
That should fix it.
当您声明数组 InputProperty[] metaData 时,您没有初始化它。 因此,当您尝试访问成员时,它根本不存在,这就是您收到错误的原因。
正如 Joel 所建议的,我建议您查看 System.Collections.Generic 中提供的集合类型,以找到合适的类型。
When you declared your array InputProperty[] metaData, you didn't initialize it. So when you tried to access a member, it just doesn't exist, which is why you got the error you did.
As Joel recommended, I'd advise you to look at the collection types provided in System.Collections.Generic for something suitable.