【问题标题】:Create number of new class objects from dictionary count从字典计数创建新类对象的数量
【发布时间】:2018-08-26 10:04:35
【问题描述】:
int proprtyCount = dictionary.Keys.Count;

 foreach (KeyValuePair<object, object> pair in dictionary)
{
     ClassCustom obj1 =new ClassCustom(pair.Key, pair.Value);
}

我需要使用 dictionary.keys.count 创建数字对象并将这些对象传递给某个集合类。

我必须将如下对象传递给集合(例如,在这种情况下,字典键计数为 3)

SomeCollection collection =new SomeCollection(obj1,obj2,obj3);

【问题讨论】:

    标签: c# .net oop collections


    【解决方案1】:

    你为什么不把它分配给一个列表呢?

    int proprtyCount = dictionary.Keys.Count;
    var classCustomList = new List<ClassCustom>();
    foreach (KeyValuePair<object, object> pair in dictionary)
    {
         classCustomList.Add(new ClassCustom(pair.Key, pair.Value));
    }
    
    SomeCollection collection = new SomeCollection(classCustomList);
    

    让 SomeCollection 类在其构造函数中初始化 classCustomList 类型的列表。

    更新:如果它是某种集合类,也许尝试做类似的事情

    int proprtyCount = dictionary.Keys.Count;
    var conditions = new PropertyCondition[propertyCount];
    int index = 0;
    foreach (KeyValuePair<object, object> pair in dictionary)
    {
        conditions[i] = new PropertyCondition(pair.Key, pair.Value));
        index++;
    }
    
    var conditionEnabledButtons = new AndCondition(conditions);
    

    数组类型有重载

    例如。

    var conditions = new PropertyCondition[3];
    conditions[0] = new PropertyCondition(AutomationElement.IsEnabledProperty, true);
    conditions[1] = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button);
    var conditionEnabledButtons = new AndCondition(conditions);
    

    【讨论】:

    • SomeCollection 类只接受 ClassCustom 格式
    • 所以列表在这种情况下没有用
    • 我不明白。为什么不发布 SomeCollection 类的代码。您始终可以更改构造函数,而不是传入 ClassCustom 类型的对象。您不知道字典键计数的数量,因此您无法按照当前的方式初始化 SomeCollection。
    • 它是我无法更改的微软自动化类
    • 现在我明白了。我认为 SomeCollection 是您制作的自定义类。下一次,也许发布您正在使用的实际 Microsoft 课程。无论如何,如果它是某种集合类,应该有一个 Add 或类似的函数。否则,您可能需要查看另一个接受 ClassCustom 集合的重载。你为什么不告诉我你正在使用什么集合类。
    猜你喜欢
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    相关资源
    最近更新 更多