2016-05-19 110 views
1

我想將字符串用作變量的一部分。將字符串用作變量的一部分

例如在下面的代碼中,我有一個名爲productLine的字符串。我想使用這個字符串中的值來創建一個變量名稱並調用這個變量的屬性「Value」。我想繼續在'productLine'中切換值,並因此繼續切換值方法被調用的變量。

有沒有辦法做到這一點,或者我是否需要重寫代碼並採取不同的方法?

foreach (string productLine in productLineData) 
{ 
    string templateKey = "{{" + productLine + "}}"; 
    string templateValue = ""; 
    if (productRow.productLine.Value != null) 
     templateValue = productRow.productLine.Value.ToString(); 
    productRowText = productRowText.Replace(templateKey, templateValue); 
} 

productRow是包含我希望使用的屬性的模型。

編輯:

productLine包含一個字符串值。例如,它首先包含productName。那時我想打電話給productRow.productName.Value。接下來'productLine'包含productPrice。那時我想打電話給productRow.productPrice.Value。等

+4

這個問題目前很混亂(可能只是一個語言問題)。你想使用一個字符串作爲變量的一部分?你有'productLine'這是填充一個字符串?你想繼續在哪裏調用值之間的切換?你需要用其他語言或例子來解釋它。 –

+0

這可能只是我缺乏理解,但我真的不知道其他問題是如何解決我的問題的。 – MeRgZaA

回答

3

您可以使用反射來做到這一點,如建議的romain-aga。

using System.Reflection; 


    //... 
    foreach (string productLine in productLineData) 
    { 
     string templateKey = "{{" + productLine + "}}"; 
     string templateValue = string.Empty; 
     object value = productRow?.GetType()?.GetProperty(productLine)?.GetValue(productRow, null); 
     if (value != null) 
      templateValue = value.ToString(); 
     productRowText = productRowText.Replace(templateKey, templateValue); 
    } 
    //... 
+1

很好的答案。我只是在調用'GetValue'之前添加了一個測試來檢查'productRow.GetType()。GetProperty(productLine)'是否爲空。:-) – aprovent

+1

你是對的。請參閱使用新語言功能編輯。 – wonko79

0

如果你想要解決的變量是一個類的屬性(即成員),那麼反射將允許您通過使用其名稱的字符串來獲取/設置其值。如果變量只是一個函數作用域符號(即string myVar = "";),那麼它在運行時不存在,並且不能被訪問。

相關問題