0

我有这样的结构:

public struct GoldAverages
    {
        public decimal Sell_GoldOunce;
        public decimal Buy_GoldOunce;
        public decimal Sell_SilverOunce;
        public decimal Buy_SilverOunce;
        public int Sell_Mazene;
        public int Buy_Mazene;
        public int Sell_Gram_18;
        public int Buy_Gram_18;
        public int Sell_Gram_24;
        public int Buy_Gram_24;
    }

我怎样才能一一读取我的结构项目(按项目名称和值)并将它们放入 Lable.text

像这样

GoldAverages Gold = new GoldAverages();
foreach (var item in Gold)
        {
            LblSummery.Text += item.name + " : " + item.value + "|";
        }
4

2 回答 2

3

你可以试试这个(你需要添加System.Reflection命名空间)

GoldAverages Gold = new GoldAverages();
Type gType = Gold.GetType();
IList<PropertyInfo> properties = new List<PropertyInfo>(gType.GetProperties());

StringBuilder sb = new StringBuilder();

foreach (PropertyInfo property in properties)
{
    string propertyName = property.Name;
    string propertyValue = property.GetValue(Gold, null);
    sb.Append(propertyName + " : " + propertyValue + " | ");
}

LblSummery.Text = sb.ToString();

现在我再次查看您的代码,您需要将字段更新为属性,我相信这就是您所追求的。否则让我知道。

于 2013-09-22T01:26:19.507 回答
-1
GoldAverage Gold = new GoldAverage();
    StringBuilder sb = new StringBuilder();
    foreach (var field in typeof(GoldAverage).GetFields())
    {
        sb.append(field.Name.ToString() + " : " + field.GetValue(Gold).ToString() + " | ");
于 2013-09-22T02:55:39.513 回答