【问题标题】:how to use more than one generic in a function in C#如何在 C# 的函数中使用多个泛型
【发布时间】:2021-12-30 05:31:39
【问题描述】:

我想为一个函数使用多个泛型,但这不起作用

  protected async Task<Tlist,T> Send<Tlist,T>(string url,HttpMethod method,DateTimeSyncedAt ) where Tlist,T:class
    {
    }

【问题讨论】:

  • Task&lt;T&gt; 只有一个通用参数。你希望做什么?
  • 这有效:protected async Task&lt;R&gt; Send&lt;T, R&gt;(T source) where T : class where R : class。这有帮助吗?
  • 是的,谢谢
  • @regestea23 - 什么“有效”?

标签: c#


【解决方案1】:

Task 不支持返回多种类型作为返回值。

所以你可以像基本上一样使用它

Task<T>
//The following wont work
Task<T,T1>

但您可以使用元组或任何 value pair

** 值对 **

元组:

元组是具有特定数量和值序列的数据结构。 Tuple 类表示一个 2 元组或对,它是一个元组 元组通常由它们的运算符使用 (T, T1) 元组中的类型可能超过两个,这取决于用例。

字典:

C# 中的字典是 System.Collection.Generics 命名空间中包含键和值的通用集合类型。

字典可以通过以下方式初始化:

    new Dictionary<string, string>(new []{new KeyValuePair<string, string>("SOMETHING1","SOMETHING2")});

如果您将此字典包装到我们的案例中称为dictionary 的变量中,您可以通过以下方式分别访问键和值

dictionary.Keys // this is an array of keys in the dictionary
dictionary.Values // this is an array of values in the dictionary

按以下方式进行:

    protected async Task<(TList, T)> Send<TList,T>(string aParam,string bParam, string cParam) where TList : IEnumerable<T> where T : struct
    {
    }

在这种情况下,这将返回一个具有指定类型的元组(item1: LIST_OF_GUID, GUID)

但您可以将其与任何类型的约束一起使用

【讨论】:

  • “任何对价值对有价值的东西”是什么意思?
  • “任何价值对价值的东西”是什么意思?
  • 对不起,它的意思是 value to value 对,它就像元组甚至字典。这些是您将值与值配对的类型。将在我的回答中描述。
  • 我已尽力向您解释。希望我能帮到你。
  • “值到值对”这句话有点奇怪。我会说“值对”或“值到值的映射”——这取决于你的实际意思。
猜你喜欢
  • 2023-01-26
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 2017-06-07
  • 1970-01-01
相关资源
最近更新 更多