【问题标题】:How to reference a struct's type parameters in a generic C# class?如何在泛型 C# 类中引用结构的类型参数?
【发布时间】:2019-06-18 11:45:48
【问题描述】:

我想创建自己的INotifyCollectionChanged 实现,但我希望可观察集合成为字典。比如:

MyObservableDictionary<KeyValuePair<TKey, TValue>>

在阅读 this article on MSDN 关于泛型之后,您似乎可以将其定义为

public class MyObservableDictionary<T> : INotifyCollectionChanged where T : struct
{
  public event NotifyCollectionChangedEventHandler CollectionChanged;
}

但是这个

  1. 不强制结构应该是类型 键值对和
  2. 我不知道如何在课堂上引用TKeyTValue

有什么解决办法吗?

【问题讨论】:

  • MyObservableDictionary&lt;TKey, TValue&gt;?
  • public class MyObservableDictionary&lt;TKey, TValue&gt; : IDictionary&lt;TKey, TValue&gt;, INotifyCollectionChanged where TValue : struct {...} - 类是字典,可观察的并且只能将值类型 (strict) 作为值。如果您希望 key 也成为结构,请添加 where TKey : struct
  • ObservableDictionary 的实现有几个例子,为什么要自己创建呢?链接:stackoverflow - .NET ObservableDictionaryGithub - kzu/ObservableDictionary.cs

标签: c# generics struct


【解决方案1】:

好吧,你有2 泛型参数,让它们成为TKeyTValue

public class MyObservableDictionary<TKey, TValue> 

你的类实现了两个接口

  1. “我希望 ... 集合成为 字典” - IDictionary&lt;TKey, TValue&gt;
  2. “我想创建自己的INotifyCollectionChanged 实现”

添加它们:

public class MyObservableDictionary<TKey, TValue> 
  : IDictionary<TKey, TValue>, 
    INotifyCollectionChanged 

最后,如果我没听错的话,你想限制TKeyTValue 都只能是struct;你可以在where的帮助下做到这一点:

 public class MyObservableDictionary<TKey, TValue> 
  : IDictionary<TKey, TValue>, 
    INotifyCollectionChanged 
  where TKey : struct
  where TValue : struct {
  //TODO: implementation here
}

【讨论】:

  • 这不是 ` where TValue : struct where TKey : struct` 意味着 TKey 将是一个结构而 TValue 是另一个结构,我想要通用结构 KeyValuePair&lt;TKey,TValue&gt;
  • 如果我理解你的意思正确,你希望TKeyTValuestruct,例如MyObservableDictionary&lt;int, double&gt;,但不是 MyObservableDictionary&lt;int, object&gt;object 不是 struct)。请注意,TKeyTValue 可以任意 struct,不必相同。
  • 可能是我的坏 Dmitry,我希望 TKeyTValue 成为结构的参数。这就是我想要的结构 KeyValuePair&lt;Tkey,TValue&gt;
  • @Themelis:KeyValuePair&lt;TKey,TValue&gt;是字典的私事;您不必对其施加任何限制。当前的 .Net (4.8) 将KeyValuePair&lt;TKey,TValue 实现为struct,接下来可以将其转换为classTKey,TValue 是唯一的问题:如果你想对它们施加约束 - 添加 where。请注意,不是任何类型,比如int 可以是struct 的一部分,也可以是class 的一部分
【解决方案2】:

你在找吗

MyObservableDictionairy<TKey, TValue> : INotifyCollectionChanged where TValue : struct

然后,您可以在添加键/值时将它们包装成键/值对,或者简单地使用这样的 add 方法签名:

public void Add(KeyValuePair<TKey, TValue> value)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多