代码之家  ›  专栏  ›  技术社区  ›  citronas

如何动态调用字典中基于映射的通用方法?

  •  0
  • citronas  · 技术社区  · 14 年前

    我有一个方法

    String Foo<T> where T: WebControl
    

    现在我有了一个类似“超链接”的字符串。想要的是打电话 Foo<Hyperlink> 基于从字符串到泛型的映射。

    这本词典得怎么看?

    它不是:

    private Dictionary<string, Type> _mapping = new Dictionary<string, Type>()
    {
          {"hyperlink", typeof(HyperLink)}
    };
    

    我想像 Foo<_mapping[mystring]> 有可能吗?如果是的话,这本词典看起来应该怎样?

    编辑 :接受的解决方案

    String _typename = "hyperlink";
    MethodInfo _mi = typeof(ParserBase).GetMethod("Foo");
    Type _type = _mapping[_typename];
    MethodInfo _mig = _mi.MakeGenericMethod(_type);
    return (String)_mig.Invoke(this, new object[] { _props }); // where _props is a dictionary defined elsewhere
    // note that the first parameter for invoke is "this", due to my method Foo is not static
    
    3 回复  |  直到 14 年前
        1
  •  1
  •   Nick Craver    14 年前

    你想要的是不可能的,因为那将是运行时(例如,字典以后可能包含任何内容)。

    如果您想通过运行时手动生成它,您可以这样做,但是您不会得到C对泛型的编译时检查。你可以通过这个 MethodInfo.MakeGenericMethod .

    这样地:

    var m = typeof(MyClass);
    var mi = ex.GetMethod("Foo");
    var mig = mi.MakeGenericMethod(_mapping["hyperlink"]);
    
    //Invoke it
    mig .Invoke(null, args);
    
        2
  •  1
  •   Restuta    14 年前

    这样是不可能的。泛型只支持编译tipe绑定。

        3
  •  1
  •   pdr    14 年前

    不,你不能那样做。您的泛型类型希望在编译时创建自己,但直到运行时才知道它是什么类型。但是,您可以使用反射。

    Type untypedGeneric = typeof(Foo<>);
    Type typedGeneric = untypedGeneric.MakeGenericType(_mapping[mystring]);