加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用GenericTypeArgument在运行时更改类型

发布时间:2020-12-15 17:35:55 所属栏目:百科 来源:网络整理
导读:这是我想要得到的 (IListFoo)listPropertyInfo.GetValue(item) 这是我如何获得Foo类型 listPropertyInfo.GetValue(item).GetType().GenericTypeArguments[0] 这是我试过但不能成功的 Convert.ChangeType(listPropertyInfo.GetValue(item),IListlistPropertyI
这是我想要得到的
(IList<Foo>)listPropertyInfo.GetValue(item)

这是我如何获得Foo类型

listPropertyInfo.GetValue(item).GetType().GenericTypeArguments[0]

这是我试过但不能成功的

Convert.ChangeType(listPropertyInfo.GetValue(item),IList<listPropertyInfo.GetValue(item).GetType().GenericTypeArguments[0]>)

这也是

((typeof(IList<>).MakeGenericType(listPropertyInfo.GetValue(item).GetType().GenericTypeArguments.Single())))(listPropertyInfo.GetValue(item))

这是我试图实现的方法

public static void trigger(IList<T> result)
{
    foreach (var item in result)
    {
        foreach (var listPropertyInfo in typeof(T).GetProperties().ToList().FindAll(x => x.PropertyType.Name == typeof(IList<>).Name))
        {
             trigger((IList<Foo>)listPropertyInfo.GetValue(item));
        }
    }
}

解决方法

我这样解决了
IList targetList = (IList)listPropertyInfo.GetValue(item);
Type foo = targetList.GetType().GenericTypeArguments.Single();
Type unboundGenericType = typeof(READ<>);
Type boundGenericType = unboundGenericType.MakeGenericType(foo);
MethodInfo doSomethingMethod = boundGenericType.GetMethod("trigger");
object instance = Activator.CreateInstance(boundGenericType);
doSomethingMethod.Invoke(instance,new object[] { targetList,f,properties });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读