是否有可能创建一个返回&#34; new KeyValuePair <t,t =“”>(key,value)&#34;

时间:2016-04-28 08:20:26

标签: c# generics methods keyvaluepair

我想要一个返回新的 KeyValuePair&lt; T,T&gt;

为什么呢?因为我想使用像

这样的方法
...
    GetAsKVP("A", "B"),
    GetAsKVP("C", "D"),
...

而不是

...
    new KeyValuePair<string, string>("A", "B"),
    new KeyValuePair<string, string>("C", "D")
...

当我将值添加到参数时KeyValuePair [] pKVP

它更快,更易读。

我试过

public static KeyValuePair<T, T> GetAsKVP(T key, T value)
{
    return new KeyValuePair<T, T>(key, value);
}

并收到错误信息;

  

类型或命名空间名称&#39; T&#39;无法找到(你错过了吗?   使用指令或程序集引用?)

3 个答案:

答案 0 :(得分:7)

T添加到方法声明:

public static KeyValuePair<T, T> GetAsKVP<T>(T key, T value)
{
    return new KeyValuePair<T, T>(key, value);
}

或者如果您想要键和值的不同类型,请使用:

public static KeyValuePair<TKey, TValue> GetAsKVP<TKey, TValue>(TKey key, TValue value)
{
    return new KeyValuePair<TKey, TValue>(key, value);
}

您可以按照描述使用它:

var kvp1 = GetAsKVP("foo", "bar");
var kvp2 = GetAsKVP(123, 456);
var kvp3 = GetAsKVP("CurrentDateTime", DateTime.UtcNow);

答案 1 :(得分:2)

试试这个,

public static KeyValuePair<TKey, TValue> GetAsKVP<TKey, TValue>(TKey key, TValue value)
{
    return new KeyValuePair<TKey, TValue>(key, value);
}

泛型方法必须定义类型参数,它们不是通过返回或接受泛型类型来暗示的。

在方法声明中使用两个具有相同名称的类型参数是没有意义的。如果键和值总是相同的类型,这可能不是很通用,你可以这样做,

public static KeyValuePair<T, T> GetAsKVP<T>(T key, T value)
{
    return new KeyValuePair<T, T>(key, value);
}

答案 2 :(得分:1)

您需要在Method标头中声明 T (名称后面)

seledCats = condsCats.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string s = "'" + string.Join("','", seledCats) + "'";
//to split into array again...
seledCats = condsCats.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

如果编译器无法自动确定数据类型,您可能希望将其添加到函数调用中:

public static KeyValuePair<T,T> GetAsKVP<T>(T key, T value)
{
    return new KeyValuePair<T, T>(key, value);
}