[英]How to add values into a variable of type object in C#
現在我是實際的代碼,成功地調試(運行)了:
object attributes = new object[] {
"key1=value1",
"key2=value2",
"key3=value3",
"key4=value4",
"keyN=valueN"
};
有時我需要更改值,所以我使用的C#詞典定義為:
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
添加值嗎?
從字典到數組的轉換
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;
將起作用(在第一種會引發運行時異常的方法中)
看起來您想將鍵和值從字典復制到字符串數組中。 您的最后一個代碼示例創建了一個字符串,但稍作修改即可解決:
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>();
您可能想看一下動態對象,可以在其中添加任何所需的對象(當然,要注意一下)。
您可以在這里找到更多關於它們的信息
然后,您可以執行以下操作:
dynamic sampleObject = new ExpandoObject();
sampleObject.number = 10;
sampleObject.Increment = (Action)(() => { sampleObject.number++; });
好的,借助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>();
}
}
現在它可以正常工作了,謝謝:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.