[英]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: 您尝试的方法至少存在三个问题:
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. base
identifier, like this
, is read-only. this
的base
标识符是只读的。 You cannot assign it. 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.