泛型、类型和数组

“通用类型”可以是数组吗?

在它存在的情况下,如何访问该数组?

您可以将给定的泛型类型 T 作为数组访问,当它是一个时,当它不是一个时,作为非数组访问?

例如:

如果我有这样的方法 ->

void MustBeOfType<T>(T value){}

我可以->

MustBeOfType<int>(10);

还有->

MustBeOfType<int[]>( new int[] { 1, 2, 3 } );

在这些通用方法中,它们能否按预期访问值?- 一个作为 int 和一个作为 int[]?

我认为 typeof(T).IsArray() 可能有一些东西......但我一生都无法弄清楚如何将参数转换为一个数组。

谢谢!


呼啦一阵风
浏览 132回答 2
2回答

眼眸繁星

你可以......但是,我不确定你应该:void MustBeOfType<T>(T value){&nbsp; Array array = value as Array;&nbsp; if (array != null) //It is an array&nbsp; {&nbsp; &nbsp; foreach (var arrayItem in array)&nbsp; &nbsp; {&nbsp; &nbsp; }&nbsp; &nbsp; for (int i = 0; i < array.Length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; var arrayItem = array.GetValue(i);&nbsp; &nbsp; }&nbsp; }&nbsp; else //It is not an array&nbsp; {&nbsp; }}

偶然的你

我不确定您要做什么,但通用类型可以是任何东西。您可以使用where子句对泛型类型进行限制,但这取决于您以及功能和上下文。让我们以列表为例。假设我们在 List 中有 List。然后我们将其定义为:List<List<string>> myListOfList = new List<List<string>>();你必须是类型也可以是任何东西(如果你没有对 where 子句施加限制)MustBeOfType<int[][]>()MustBeOfType<List<List<string>>>()MustBeOfType<AnyOtherGenericClass<List<string>>>()并能够访问它:class MustBeOfType<T>{&nbsp; &nbsp; private T _value;&nbsp; &nbsp; MustBeofType(T value)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;_value = value;&nbsp; &nbsp; }}为了能够对 进行操作,您可以使用反射,或者如果您放置了 where 限制并且您的 where 限制具有 Type,那么您可以看到该 Type 的属性。
打开App,查看更多内容
随时随地看视频慕课网APP