简体   繁体   中英

Cast int[] into MyType[] where MyType inherited from Enum?

I try to cast an int array int[] into Rights array Rights[] , Rights is Enum by example... But it can be other type than rights but always inherited from Enum . I got the final type in a Type variable. I can create the Enum[] array but not the final Rights[] array for my methodInfo.Invoke(obj,param.ToArray()) .

List<object> param = new List<object>();
ParameterInfo pi = ...
if (pi.ParameterType.IsArray && pi.ParameterType.GetElementType().IsEnum)
{
    List<Enum> enums = new List<Enum>();
    foreach (int i in GetTabInt())
    {
        enums.Add((Enum)Enum.ToObject(pi.ParameterType.GetElementType(), i));
    }
    param.Add(enums.ToArray()); // got Enum[] not Rights[]
}

Thank you for helping me!

You need to create an array of the appropriate type. Since the type isn't known at compile time, you must use Array.CreateInstance() . You can use this helper method.

public Array ToEnumArray(Type type, ICollection values)
{
    if (!typeof(Enum).IsAssignableFrom(type))
        throw new ArgumentException(String.Format("Type '{0}' is not an Enum", type));
    var result = Array.CreateInstance(type, values.Count);
    var i = 0;
    foreach (var value in values)
        result.SetValue(Enum.ToObject(type, value), i++);
    return result;
}

Then you could use it like so:

ParameterInfo pi = ...;
if (pi.ParameterType.IsArray && pi.ParameterType.GetElementType().IsEnum)
{
    var enumArray = ToEnumArray(pi.ParameterType.GetElementType(), GetTabInt());
    param.Add(enumArray);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM