Dynamic cast to generic type

限于喜欢 提交于 2019-12-05 10:23:09

You have some IObjectProvider<T>. If T is a type know at compile-time, you can just use a cast. For example, if T was Foo:

IObjectProvider<Foo> provider = …;
var predicate = (Predicate<Foo>)predicateProperty.GetValue(
    invocation.InvocationTarget, null);
Foo item = provider.Get(predicate);

EDIT: It seems you don't know T at compile time. This means you have two options:

  1. Use dynamic:

    object provider = …
    object predicate = predicateProperty.GetValue(
        invocation.InvocationTarget, null);
    object item = ((dynamic)provider).Get((dynamic)predicate);
    
  2. Use reflection:

    object provider = …;
    object predicate = predicateProperty.GetValue(
        invocation.InvocationTarget, null);
    var getMethod = provider.GetType().GetMethod("Get");
    object item = getMethod.Invoke(provider, new[] { predicate });
    
pm100

This question shows a lot of confusion about types, var etc.

This is a meaningless sentence

It is of type var and GetValue turned it into an object.

I think you are saying

I have some code that needs a Predicate<T>

You have some code (that you don't show us) that returns an Object. And want somehow to coerce that return value into a Predicate<T>. If the returned object is a Predicate<T> then simply go (Predicate<T>)retobj - and you are done. If it's not a type that can be cast to Predicate<T> then no amount of jiggling will make it into a Predicate<T>.

I do this way

public T CastToType<T>(object objType, T type) where T : class
    {
        var cast = objType as T;

        if(cast == null)
            throw new InvalidCastException();

        return cast;
    }

And like this

var test = CastToType(objType, new ArrayList());

test will be have ArrayList type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!