问题
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
}
回答1:
Since the size of your Items collection can vary, you should use a collection type like List<T>
or Dictionary<K,V>
instead of an array.
回答2:
For the current compiler error, you need to initialize the metaData array, like:
InputProperty[] metaData = new InputProperty[](nvPairs.Count);
Using linq you could:
private Update BuildMetaData(NameValueCollection nvPairs)
{
Update update = new Update();
update.Items = nvPairs.Keys
.Select(k=> new InputProperty
{
Name = "udf:" + k,
Val = nvPairs[k] // or Values = nvPairs.GetValues(k)
}
)
.ToArray();
return update; // return the Update object
}
回答3:
If I'm not mistaken, your InputProperty array is never initialized. If you change line 2 to this:
InputProperty[] metaData = new InputProperty[nvPairs.Count];
That should fix it.
回答4:
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.
来源:https://stackoverflow.com/questions/663416/populate-array-of-objects-from-namevaluecollection-in-c-sharp