【问题标题】:Define maximum for NumerictUpDown in a dictionary在字典中定义 NumerictUpDown 的最大值
【发布时间】:2016-03-17 09:58:52
【问题描述】:

所以我有一个字典,其中包含一些名为controlDict 的控件。但是,如果我想像这样为 NumericUpDown 控件设置最大值:

controlDict.Add("amountNum" + i.ToString(), new NumericUpDown());
            controlDict["amountNum" + i.ToString()].Location = new Point(60, 42);
controlDict["amountNum" + i.ToString()].Maximum = new decimal(new int[] {
            -1,
            -1,
            -1,
            0});

它给了我这个错误:

“Control”不包含“Maximum”的定义,并且找不到接受“Control”类型的第一个参数的扩展方法“Maximum”(您是否缺少 using 指令或程序集引用?)

我该如何解决这个问题?

【问题讨论】:

    标签: c# winforms dictionary controls


    【解决方案1】:

    您应该将控件强制转换为NumericUpDown,然后为其属性赋值:

    var numeric = (NumericUpDown)controlDict["amountNum" + i.ToString()];
    numeric.Maximum = 100;
    

    为什么controlDict["amountNum" + i.ToString()].Location 有效 没有铸造?

    因为结果是Control 并且控件类有Location 属性。并且您的所有控件,包括 NumericUpDown 都继承自 Control

    您的字典中的项目是Control 类型。当您使用controlDict["key"] 从字典中获取项目时,结果是Control 类型。因此您可以访问Control 类的所有属性。 当您知道结果控件是特定控件类型时,要访问特定控件属性,您应该将其强制转换为特定控件类型。

    【讨论】:

      【解决方案2】:

      这是因为 controlDict["amountNum" + i.ToString()] 是 Control 实例。 试试这个:

      (controlDict["amountNum" + i.ToString()] as NumericUpDown).Maximum = new decimal(new int[] {
              -1,
              -1,
              -1,
              0});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-19
        • 2010-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多