[英]Convert.ChangeType to produce an array of concrete type elements, not objects
Struggling with the following problem. 挣扎着以下问题。 I have an attribute that defines the name of the key in the database table.
我有一个属性,用于定义数据库表中键的名称。 Using reflection, I initialize the value of a property or a field with that attribute.
使用反射,我使用该属性初始化属性或字段的值。 Everything is great until I define my property as an array:
在将我的属性定义为数组之前,一切都很棒:
[ConfigurationKey("TestArray")]
public int[] Array { get; set; }
Assuming that values stored in the table are comma-delimited strings, I am using the following to create an array: 假设存储在表中的值是逗号分隔的字符串,我使用以下命令创建一个数组:
return valueString.Split(',').Select(s => Convert.ChangeType(s, memberType.GetElementType())).ToArray();
This does create an array of elements but only array of Objects. 这确实创建了一个元素数组,但只创建了一个对象数组。 As a result when I use FieldInfo or PropertyInfo to set a value, it throws with the exception "Cannot assign
Object[]
to Int32[]
". 因此,当我使用FieldInfo或PropertyInfo设置一个值时,它抛出异常“无法将
Object[]
赋值给Int32[]
”。
Any ideas? 有任何想法吗?
Well given that Convert.ChangeType
is declared to return Object
, I don't think this is particularly surprising. 鉴于
Convert.ChangeType
被声明为返回Object
,我认为这并不特别令人惊讶。 ToArray()
will create an array with the same element type as the input sequence, and Select
is going to return an IEnumerable<object>
in this case. ToArray()
将创建一个与输入序列具有相同元素类型的数组,在这种情况下, Select
将返回IEnumerable<object>
。
One option is to call Cast
(and then ToArray
) using reflection. 一种选择是使用反射调用
Cast
(然后使用ToArray
)。 To be honest, it's probably going to be easiest to put everything into a single generic method, and call that by reflection: 说实话,将所有内容放入一个通用方法中可能最简单,并通过反射调用它 :
public static T[] ParseToArray<T>(string valueString)
{
return valueString.Split(',')
.Select(s => (T) Convert.ChangeType(s, typeof(T))
.ToArray();
}
Then you'd need: 然后你需要:
Type t = memberType.GetElementType();
// Use the type declaring ParseToArray here
MethodInfo methodDefinition = typeof(...).GetMethod("ParseToArray");
MethodInfo method = methodDefinition.MakeGenericMethod(t);
object array = method.Invoke(null, new object[] { valueString });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.