开发者

How to get an array of types from an array of objects?

开发者 https://www.devze.com 2023-02-05 17:49 出处:网络
I have an object[] which I am using to dynamically invoke a method via reflection. Due to an AmbiguousMatchException I need to know the types, and it would be difficult to know them ahead of time. So

I have an object[] which I am using to dynamically invoke a method via reflection. Due to an AmbiguousMatchException I need to know the types, and it would be difficult to know them ahead of time. So I want to take the "params object[] args" and get a Type[] of all of th开发者_StackOverflow社区ose.


If you have linq available you can easily get an array of types that matches the objects but I'm not exactly sure it will help in your end goal.

var types = args.Select(arg => arg.GetType()).ToArray();

Is it your intention to inspect the object array for types and then inspect the method signature and try to match them up appropriately?


Please try this:

        IList<Type> typeList = new List<Type>();

        foreach(object item in args)
        {
            typeList.Add(item.GetType());
        }

        typeList.ToArray();


Give the Array.ConvertAll function a shot:

Type[] objTypes = Array.ConvertAll<object, Type>(
    objArray,
    delegate(object obj){
        if(obj==null) return null;
        return obj.GetType();
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号