填充对象数组在C#中的NameValueCollection [英] Populate array of objects from namevaluecollection in c#

查看:227
本文介绍了填充对象数组在C#中的NameValueCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C#。这是一个硬codeD的事情我得到了工作:

  InputProperty grantNumber =新InputProperty();
grantNumber.Name =UDF:授权号;
grantNumber.Val =571-1238;更新更新=新Update();
update.Items =新InputProperty [] {} grantNumber;

现在我想概括这种支持在更新对象的项目数不确定,我想出了这一点,但它无法编译:

 更新更新= BuildMetaData(NVC); //调用函数来构建更新对象

和本身的功能在这里:

 私人更新BuildMetaData(NameValueCollection中nvPairs)
{
    更新更新=新Update();
    InputProperty []元数据; //声明InputProperty对象数组
    INT I = 0;
    的foreach(在nvPairs.Keys字符串键)
    {
        元数据由[i] =新InputProperty(); //编译器会在此行
        元数据[I] .Name点=UDF:+键;
        的foreach(在nvPairs.GetValues​​字符串值(键))
            元数据[I] .VAL =价值;
    }
    update.Items =元数据;
    返回更新; //返回更新的对象
}


解决方案

由于你的项目的大小集合可以改变,你应该使用一个集合类型如列表< T> 词典< K,V方式> 而不是数组

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
}

解决方案

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.

这篇关于填充对象数组在C#中的NameValueCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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