【问题标题】:How to add values into a variable of type object in C#如何在 C# 中将值添加到类型对象的变量中
【发布时间】:2015-05-27 08:30:52
【问题描述】:

现在我是实际代码的样子,它正在成功调试(运行):

object attributes = new object[] { 
                  "key1=value1",
                  "key2=value2",
                  "key3=value3",
                  "key4=value4",
                  "keyN=valueN" 
};

有时我需要更改值,所以我使用 C# Dictionary 定义为:

public Dictionary<string,string> dAttributes=new Dictionary<string,string>();

我正在字典中一一添加KEY和VALUE。但是当我尝试进行类型转换(我认为这是不可能的)或应用任何其他逻辑时,名为“属性”的对象中的值的格式不正确。

首先我尝试了这个:

object attributes = new object[]{dAttributes};

然后我这样做了:

            int i=0;
            string attribueKeyAndValues;
            attribueKeyAndValues = "";
            foreach (KeyValuePair<string,string> item in dAttributes)
            {
                if(i==(dealAttributes.Count-1))
                    attribueKeyAndValues+="\"" +item.Key+"="+item.Value+"\"";
                else
                    attribueKeyAndValues += "\"" + item.Key +"="+ item.Value + "\"" + ",";
                i++;
            }

            attributes = new object[] { attribueKeyAndValues };

现在这段代码不起作用,因为attribute 将整个字符串作为单个值。另外更重要的是,当我调试代码并快速查看 attribueKeyAndValues(在 Text Visualizer 中)中的值时,我会看到 "\key=value\","\key=value\" 等等。

还有其他方法可以在attribute 中添加值吗?

【问题讨论】:

  • 当然不行,因为attributeKeyAndValue是单个字符串而不是字符串数组。另请记住,如果您使用字典,则无法保证顺序。
  • 嗯,这里似乎有些奇怪。为什么要从引用 object[]object 开始,而 object[] 本身只包含字符串?为什么不从 string[] 开始,完全避开 object

标签: c# object generics dictionary


【解决方案1】:

从字典到数组的转换

attributes = dAttributes.Select(a=>a.Key+"="+a.Value).ToArray();

这里使用了协变数组转换(ToArray()返回string[],但可以赋值给object[]变量)

但如果你真的需要object[],请进行演员表

attributes = dAttributes.Select(a=>(object)(a.Key+"="+a.Value)).ToArray();

然后像attributes[0] = 1; 这样的东西会起作用 (在第一个会抛出运行时异常的方法中)

【讨论】:

  • @phoog,object[] o = new string[4];是协变数组转换; attributes 可以是 object[]。可以使用attributes[0]="string"attributes[0]=1 会引发运行时异常
  • 同意。但是,原始示例不使用协变数组转换,attributes[0]=1 不会引发异常。因此,您的解决方案不等同于示例代码。
  • 那行得通,然后我尝试了我在此处发布的以下代码。非常感谢:)
  • @phoog,确实如此。我在答案中添加了更多细节
  • 但是当你可以打电话给ToArray&lt;object&gt;()时,为什么还要进行所有这些转换呢?
【解决方案2】:

您似乎想将字典中的键和值复制到字符串数组中。您的最后一个代码示例创建了一个字符串,但稍作修改即可修复它:

int i=0;
var attributes = new object[dAttributes.Count];
string attribueKeyAndValues = "";
foreach (KeyValuePair<string,string> item in dAttributes)
{
    result[i] = item.Key + "=" + item.Value;
    i++;
}

顺便说一句,使用字符串数组而不是对象数组可能会更好:

int i=0;
var attributes = new string[dAttributes.Count];
string attribueKeyAndValues = "";
foreach (KeyValuePair<string,string> item in dAttributes)
{
    result[i] = item.Key + "=" + item.Value;
    i++;
}

最后,您可以使用 LINQ 做到这一点:

var attributes = dAttributes.Select(item => item.Key + "=" + item.Value).ToArray();

或者,如果你真的需要它是一个对象数组而不是字符串数组,你可以这样做:

var attributes = dAttributes.Select(item => item.Key + "=" + item.Value).ToArray<object>();

【讨论】:

    【解决方案3】:

    你可能想看看动态对象,你可以在其中添加任何你想要的东西(当然,有通常的警告)。

    您可以在此处找到有关它们的更多信息

    然后您可以执行以下操作:

    dynamic sampleObject = new ExpandoObject();
    sampleObject.number = 10;
    sampleObject.Increment = (Action)(() => { sampleObject.number++; });
    

    【讨论】:

      【解决方案4】:

      好的,在 ASH 的回答的帮助下,我和我的另一个朋友成功地解决了这个问题,

      public static class AttributeExtensions
          {
              public static object ToAttributeArray(this DAttributes dealAttr)
              {
                  var objectsColl = dealAttr.dAttributes.Select(x => x.Key + "=" + x.Value);
      
                  var objArray = objectsColl.Cast<object>();
                  return  objArray.ToArray<object>();
      
              }
          }
      

      现在它可以正常工作了,谢谢你们:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-09
        • 1970-01-01
        • 2010-11-09
        • 2022-06-27
        • 1970-01-01
        相关资源
        最近更新 更多