【问题标题】:Is it possible to concreate variable in c# [duplicate]是否可以在c#中创建变量[重复]
【发布时间】:2021-12-29 14:41:54
【问题描述】:

我有一些变量和结果正在进入数据库。

例如

        float[] qty1;
        Quote quote = new Quote();
        quote.qty1 = qty1[0];
        quote.qty2 = qty1[1];
        quote.qty3 = qty1[2];
        quote.qty4 = qty1[3];

我试图让这个过程更加动态

           for (int i = 0; i <= 3; i++)
            {
            
            quote.qtyi = qty1[i];
            }

请帮助我如何使用 quote.qtyi 和 i 的值,因此它将显示为 quote.qty1、quote.qty2、quote.qty3、quote.qty4

【问题讨论】:

  • 也许Quote.qtyx 也应该是一个数组,就像qtyx 一样?那将是最好的解决方案
  • @HimBromBeere 是的,虽然我怀疑Quote 可能是第一句话的数据库实体。

标签: c# asp.net c#-4.0 c#-3.0 c#-2.0


【解决方案1】:

使用反射:

for (int i = 0; i <= 3; i++)
        {
        
        quote.GetType().GetProperty("qty"+i).SetValue(quote,qt1[i]);

        }

quote.getType().getProperty("qty"+i) -> 从对象“quote”中获取名为“qty”+i的属性。

.setValue(quote,qt1[i]) -> 将值“qt1[i]”设置为对象“quote”的属性(如果她存在)。

我的第一个答案有错字,现在可以编译了

【讨论】:

  • 纯代码的答案特别没有帮助。解释你做了什么以及为什么,还要列出潜在的问题(例如使用反射的性能)
  • 尤其是当他们甚至不编译时
  • 已经编辑,有一些错别字现在应该可以工作了
猜你喜欢
  • 1970-01-01
  • 2014-01-22
  • 2019-07-04
  • 1970-01-01
  • 2017-03-17
  • 2017-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多