简体   繁体   English

C#在派生类中设置基础对象

[英]C# Set Base Object in Derived Class

I have the following class: 我有以下课程:

public class MyDict: ConcurrentDictionary<int, string>
{
    public GenerateContent()
    {
        for(int i = 0 ; i < 10 ; i++)
        {
            this.TryAdd(i, i.ToString());
        }

        base = this.OrderByDescending(v => v.Key); // --> Error
    }
}

After adding some values to the base class, I would like to sort it. 在向基类添加一些值之后,我想对它进行排序。 But ConcurrentDictionary<> does not offer a Sort() method. ConcurrentDictionary<>不提供Sort()方法。 Therefore I used OrderByDescending() . 因此我使用了OrderByDescending() But this method does not change the original object. 但是这种方法不会改变原始对象。 It returns a new one instead. 它会返回一个新的。

Is there a way to sort the dictionary? 有没有办法对字典进行排序?

There are at least three problems with the approach you're attempting: 您尝试的方法至少存在三个问题:

  1. First and foremost, as commenter Rob points out , ConcurrentDictionary<TKey, TValue> does not preserve order. 首先, 正如罗伯特指出的那样ConcurrentDictionary<TKey, TValue>不保留顺序。 It has no mechanism for ordering, and if it did, that order wouldn't be guaranteed in the future. 它没有订购机制,如果确实如此,将来不会保证该订单。
  2. The base identifier, like this , is read-only. thisbase标识符是只读的。 You cannot assign it. 你不能分配它。
  3. The type of base would be ConcurrentDictionary<int, string> (in your example), but the type of the OrderByDescending() method's return value is IEnumerable<KeyValuePair<int, string>> and so would not be assignable to the variable base anyway. base类型是ConcurrentDictionary<int, string> (在您的示例中),但OrderByDescending()方法的返回值的类型是IEnumerable<KeyValuePair<int, string>>因此无论如何都不能赋值给变量base

If you want an ordered dictionary, you'll need to use something else, eg SortedDictionary<TKey, TValue> or SortedList<TKey, TValue> . 如果你想要一个有序的字典,你需要使用其他东西,例如SortedDictionary<TKey, TValue>SortedList<TKey, TValue> Of course, neither of those are thread-safe, so you would need to take additional steps to make use of them safely if they are used concurrently. 当然,这些都不是线程安全的,因此如果同时使用它们,您需要采取额外的步骤来安全地使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM