如何从类型转换为通用? [英] How do I convert from type to generic?

查看:151
本文介绍了如何从类型转换为通用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HY有

给出的这个类:

public static class FooClass<TFoo>
{
    public static TFoo FooMethod(object source)
    {
        // implementation goes here
    }
}

现在我想创建这个类:

public static class FooClass
{
    public static object FooMethod(object source, Type fooType)
    {
        var classType = typeof (FooClass<>).MakeGenericType(fooType);
        var methodInfo = classType.GetMethod("FooMethod", new[]
        {
            typeof (object)
        });
        // WHAT NOW?!
    }
}



也提到:

also to mention:


  • FooMethod 的重载在 FooClass< TFoo> ,但我只是想给访问中提到过载(签名匹配 - 除了paramterNames)

  • 的返回类型对象将succifient

  • 我不能让 FooMethod FooClass 通用 - 它应该是一个旧式界面,因为它会从反射代码中使用

  • there are overloads of FooMethod in FooClass<TFoo>, but i only want to give access to mentioned overload (signature is matching - except paramterNames)
  • returnType object would be succifient
  • i cannot make FooMethod in FooClass generic - it should be an "oldstyle" interface, as it will be used from reflection-code

推荐答案

是这样的:

public static class Foo
{
    public static object FooMethod(object source, Type fooType)
    {
        return typeof(Foo<>).MakeGenericType(fooType)
            .GetMethod("FooMethod").Invoke(null, new object[] { source });
    }
}



然而 - 这种反思可以在一个紧密的循环慢;如果你正在做这个地段,我会被诱惑扭转依赖,因此通用的代码调用到非通用代码:

however - this reflection can be slow in a tight loop; if you are doing this lots, I would be tempted to reverse the dependency, so the generic code calls into the non-generic code:

public static class Foo<TFoo>
{
    public static TFoo FooMethod(object source)
    {
        return (TFoo)Foo.FooMethod(source, typeof(TFoo));
    }
}



(与在非通用版本的执行)

(with the implementation in the non-generic version)

这篇关于如何从类型转换为通用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆