If I have a MethodInfo on a closed generic Type is there an easy way to switch those types?

前端 未结 4 1469
醉酒成梦
醉酒成梦 2020-12-06 12:26

Let\'s say that I have the methodInfo for something like Nullable.HasValue. Is there anyway to convert it to Nullable.HasValue

4条回答
  •  臣服心动
    2020-12-06 12:57

    You can do it easily with a little more reflection. You can't do it magically without reflection.

        static void Main(string[] args)
        {
            PropertyInfo intHasValue = typeof (int?).GetProperty("HasValue");
            PropertyInfo boolHasValue = ChangeGenericType(intHasValue, typeof (bool));
        }
    
        public static PropertyInfo ChangeGenericType(PropertyInfo property, Type targetType)
        {
            Type constructed = property.DeclaringType;
            Type generic = constructed.GetGenericTypeDefinition();
            Type targetConstructed = generic.MakeGenericType(new[] {targetType});
            return targetConstructed.GetProperty(property.Name);
        }
    

    Of course this is pretty specific to only work for generic types with a single type parameter but it could be generalized to do more if needed.

提交回复
热议问题