开发者

Conver Type class to a generic argument

Lets say I have a function

public void func1<T>();

And another function:

public void func2(Type type);

Inside func2, I want to call func1 with type. how can I "Convert" the type so it can fit in?

edit: I didn't thought it will matter, but func1 is not my function. it part of the framework:

context.CreateObjectSet<T>开发者_如何转开发;()


You cannot call the generic function explicitly because you do not know the type at compile time. You can use reflections to call func1 and specify your type as generic argument. However I would advise you to change the signature of the methods to avoid using reflections if possible.

Here is an example of how to do it with Reflections:

    private static void Method1(Type type)
    {
        MethodInfo methodInfo = typeof(Program).GetMethod("Method2", BindingFlags.NonPublic | BindingFlags.Static);
        MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(type);
        genericMethodInfo.Invoke(null, null);
    }

    private static void Method2<T>()
    {
        Console.WriteLine(typeof(T).FullName);
    }


You would have to use reflection.

public void func2(Type type)
{
    // call func1<T>()
    var thisType = this.GetType();
    var method = thisType.GetMethod("func1", new Type[0]).MakeGenericMethod(type);
    method.Invoke(this, null);
}


Another option, of course: you can simply go the other direction and make the Type version the "real" one:

public T func1<T>() 
{
    func2(typeof(T));
}

public object func2(Type type)
{
    Console.WriteLine(type.FullName);
}

This is similar to how the framework implements Enum.TryParse<TEnum> and Enum.TryParseEnum. The implementation of the generic TEnum variant simply passes it along (via typeof(TEnum)) to the non-generic (Type-based) method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜