c# 数组泛型,每个数组项的类型不同

本文关键字:数组 类型 泛型 | 更新日期: 2023-09-27 18:35:24

我有一个结构来定义一些使用泛型的对类型:

struct SomeNameValuePair<T>
{
    string TypeName;
    T Value;
}

并且需要声明一个 SomeNameValuePair 数组:

SomeNameValuePair<T>[] someNameValuePair=new SomeNameValuePair<T>[3];

问题是我需要不同数组项的 Value 属性的不同类型。在代码中,它更容易理解:

SomeNameValuePair<int> tempSomeNameValuePair0;
tempSomeNameValuePair0.TypeName="int";
tempSomeNameValuePair0.Value=10;

SomeNameValuePair<double> tempSomeNameValuePair1;
tempSomeNameValuePair1.TypeName="double";
tempSomeNameValuePair1.Value=10.5;
tempSomeNameValuePair2.TypeName="string";
tempSomeNameValuePair2.Value="Random String";
someNameValuePair[0]=tempSomeNameValuePair0
someNameValuePair[1]=tempSomeNameValuePair1
someNameValuePair[2]=tempSomeNameValuePair2

显然,我的代码在实例化数组someNameValuePair=new SomeNameValuePair<T>[3];时不起作用,我将其项目的数组属性值提交为 T 类型。

有什么方法可以在 C# 中实现我的目标吗?

c# 数组泛型,每个数组项的类型不同

你需要一个非泛型基类:

class SomeNameValuePairBase
{
    string TypeName;
}

然后,所有泛型项都继承自此基类:(它的类,而不是结构,因为结构不能使用继承)

class SomeNameValuePair<T> : SomeNameValuePairBase
{
    T Value;
}

这样就可以声明一个项目数组:

SomeNameValuePairBase[] someNameValuePair = new SomeNameValuePairBase[3];

并像这样使用它:

someNameValuePair[0] = new SomeNewValuePair<double>();

此外,不应使用"TypeName",而应改用 C# "is" 运算符:

if(someValuePair[0] is someValuePair<double>) ...