简体   繁体   English

如何将“Type”类型的变量传递给泛型参数

[英]How to pass variable of type “Type” to generic parameter

I'm trying to do this: 我正在尝试这样做:

Type type = Type.GetType(string.Format("Gestor.Data.Entities.{0}, Gestor.Data", e.Item.Value));
MetaDataUtil.GetColumnasGrid<type>();

but it's not working, do you have any idea how I could do this? 但它不起作用,你知道我怎么能这样做吗?

You need to use reflection for this. 你需要使用反射。

var method =
    typeof(MetaDataUtil)
    .GetMethod("GetColumnasGrid")
    .MakeGenericMethod(new [] { type })
    .Invoke(null, null);

If it is an instance method instead of a static method, then you pass the variable to Invoke(the second parameter null is for an array of parameters that you would usually pass to the method, in the case of null is like calling a method with no parameters .GetColumnAsGrid() ): 如果它是一个实例方法而不是静态方法,那么你将变量传递给Invoke(第二个参数null用于通常传递给方法的参数数组,在null的情况下就像调用一个方法一样没有参数.GetColumnAsGrid() ):

Type genericTypeParameter = Type.GetType(string.Format("Gestor.Data.Entities.{0}, Gestor.Data", e.Item.Value));
MetaDataUtil someInstance = new MetaDataUtil();

var returnResult =
    typeof(MetaDataUtil)
    .GetMethod("GetColumnsAsGrid")
    .MakeGenericMethod(new [] { genericTypeParameter })
    .Invoke(someInstance, null);//passing someInstance here because we want to call someInstance.GetColumnsAsGrid<...>()

If you have ambiguous overload exception it's probably because GetMethod found more than one method with that name. 如果你有不明确的重载异常,可能是因为GetMethod找到了多个具有该名称的方法。 In which case you can instead use GetMethods and use criteria to filter down to the method you want. 在这种情况下,您可以改为使用GetMethods并使用条件过滤到您想要的方法。 This can be kind of fragile though because someone might add another method similar enough to your criteria that it then breaks your code when it returns multiple methods: 这可能有点脆弱,因为有人可能会添加另一个类似于你的标准的方法,然后当它返回多个方法时它会破坏你的代码:

var returnResult = 
    typeof(MetaDataUtil)
    .GetMethods().Single( m=> m.Name == "GetColumnsAsGrid" && m.IsGenericMethod 
        && m.GetParameters().Count() == 0 //the overload that takes 0 parameters i.e. SomeMethod()
        && m.GetGenericArguments().Count() == 1 //the overload like SomeMethod<OnlyOneGenericParam>()
    )
    .MakeGenericMethod(new [] { genericTypeParameter })
    .Invoke(someInstance, null);

This isn't perfect because you could still have some ambiguity. 这并不完美,因为你仍然可能有些含糊不清。 I'm only checking the count and you'd really need to iterate through the GetParameters and GetGenericArguments and check each one to make sure it matches the signature that you want. 我只是检查计数,你真的需要迭代GetParameters和GetGenericArguments并检查每一个以确保它匹配你想要的签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM