在2017年创建通用属性实现的任何好方法?

时间:2022-02-01 16:14:53

I was reviewing this url on generics in C# but I'm unclear on how to implement the generic implementation I have in mind:

我正在审查C#中关于泛型的这个URL,但我不清楚如何实现我想到的泛型实现:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods

I need to create a custom KeyValuePair class for downstream serialization. Downstream json serialization converts a native .net Dictionary into a generic javascript object which adds complexity and overhead so I need to create a custom KeyvaluePair class.

我需要为下游序列化创建一个自定义KeyValuePair类。下游json序列化将原生.net字典转换为通用javascript对象,这增加了复杂性和开销,因此我需要创建一个自定义KeyvaluePair类。

However, I want to make this custom KeyValuePair class generic so the key or value can either be an int or string. What would be the most elegant way to implement this in C#? The following code is incorrect but demonstrates what I'm looking for:

但是,我想使这个自定义KeyValuePair类通用,因此键或值可以是int或string。在C#中实现它的最优雅的方法是什么?以下代码不正确,但演示了我正在寻找的内容:

public class KeyValuePair
{
    public <T> Key { get; set; }
    public <T> Value { get; set; }
}

I did some googling and the only references I found were a few years old and the implementations seemed a bit hacky. Not sure if there's a better way to do this in 2017....

我做了一些谷歌搜索,我发现的唯一参考是几年,实施似乎有点hacky。不确定2017年是否有更好的方法来做到这一点....

1 个解决方案

#1


0  

The following implementation works perfectly:

以下实现完美地运行:

public class MyCustomKeyValuePair<T1, T2>
{
    public T1 Key { get; set; }
    public T2 Value { get; set; }
}

Thanks for the pointer @litelite!

感谢指针@litelite!

#1


0  

The following implementation works perfectly:

以下实现完美地运行:

public class MyCustomKeyValuePair<T1, T2>
{
    public T1 Key { get; set; }
    public T2 Value { get; set; }
}

Thanks for the pointer @litelite!

感谢指针@litelite!