c#使用反射检索数组元素的类型

编程入门 行业动态 更新时间:2024-10-21 03:32:32
本文介绍了c#使用反射检索数组元素的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何根据以下代码使用反射实例化数组属性?

How do I instantiate an array property using Reflection based on the code below?

public class Foo { public Foo() { foreach(var property in GetType().GetProperties()) { if (property.PropertyType.IsArray) { // the line below creates a 2D array of type Bar. How to fix? var array = Array.CreateInstance(property.PropertyType, 0); property.SetValue(this, array, null); } } } public Bar[] Bars {get;set;} } public class Bar { public string Name {get;set;} }

推荐答案

Array.CreateInstance 需要数组的元素类型.您传递整个属性类型,正如您刚刚通过检查 property.PropertyType.IsArray 发现的那样,一个数组类型(特别是 Bar[] - 即一个Bar 元素的数组).

The first parameter of Array.CreateInstance expects the element type of the array. You pass the entire property type, which is, as you have just found out by checking property.PropertyType.IsArray, an array type (specifically, Bar[] - i.e. an array of Bar elements).

要获取数组类型的元素类型,请使用其GetElementType 方法:

To get the element type of an array type, use its GetElementType method:

var array = Array.CreateInstance(property.PropertyType.GetElementType(), 0);

我想你会在需要时用更大的数字替换传递给第二个参数的零,除非你真的只想要空数组.

更多推荐

c#使用反射检索数组元素的类型

本文发布于:2023-10-27 03:16:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532151.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   反射   元素   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!