是否可以创建一个返回"new KeyValuePair <T,T>(key,value)"的方法

Fur*_*nci 0 c# generics methods keyvaluepair

我想要一个返回新KeyValuePair <T,T>的方法

为什么?因为我想使用像这样的方法

...
    GetAsKVP("A", "B"),
    GetAsKVP("C", "D"),
...
Run Code Online (Sandbox Code Playgroud)

代替

...
    new KeyValuePair<string, string>("A", "B"),
    new KeyValuePair<string, string>("C", "D")
...
Run Code Online (Sandbox Code Playgroud)

当我向params KeyValuePair [] pKVP添加值时

它更快,更易读.

我试过了

public static KeyValuePair<T, T> GetAsKVP(T key, T value)
{
    return new KeyValuePair<T, T>(key, value);
}
Run Code Online (Sandbox Code Playgroud)

并得到一个错误;

找不到类型或命名空间名称"T"(您是否缺少using指令或程序集引用?)

Sze*_*eki 7

添加T到方法声明:

public static KeyValuePair<T, T> GetAsKVP<T>(T key, T value)
{
    return new KeyValuePair<T, T>(key, value);
}
Run Code Online (Sandbox Code Playgroud)

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

public static KeyValuePair<TKey, TValue> GetAsKVP<TKey, TValue>(TKey key, TValue value)
{
    return new KeyValuePair<TKey, TValue>(key, value);
}
Run Code Online (Sandbox Code Playgroud)

您可以按照描述使用它:

var kvp1 = GetAsKVP("foo", "bar");
var kvp2 = GetAsKVP(123, 456);
var kvp3 = GetAsKVP("CurrentDateTime", DateTime.UtcNow);
Run Code Online (Sandbox Code Playgroud)