.NET反思 - 如何获得"真正的"从出信息参数类型 [英] .NET Reflection - How to get "real" type from out ParameterInfo

查看:151
本文介绍了.NET反思 - 如何获得"真正的"从出信息参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证一个参数既是out参数和扩展的接口(ICollection的)。反射API似乎并不想给我的真实类型的参数,只有一个与&放大器;在结束这将不会在一个IsAssignableFrom语句正确评估。我已经写了一些C#code,它的工作原理,但它似乎应该有更好的方式来做到这一点。

I'm trying to validate that a parameter is both an out parameter and extends an interface (ICollection). The reflection api doesn't seem to want to give me the "real" type of the parameter, only the one with an "&" at the end which will not evaluate correctly in an IsAssignableFrom statement. I've written some c# code that works but it seems like there should be a better way to do this.

bool isCachedArg(ParameterInfo pInfo)
{    
    if (!pInfo.IsOut)
        return false;

    string typeName = pInfo.ParameterType.FullName;
    string nameNoAmpersand = typeName.Substring(0, typeName.Length - 1);
    Type realType = Type.GetType(nameNoAmpersand);

    if (!typeof(ICollection).IsAssignableFrom(realType))
        return false;

    return true;
}

有没有办法得到的RealType无需重新加载从字符串名称的类型?我仍然在.NET 2.1。

Is there a way to get realType without reloading the Type from its string name? I'm still on .NET 2.1.

谢谢, 兰迪

推荐答案

这是退出参数是被裁判 - 所以你会发现 pInfo.ParameterType.IsByRef 返回true。为了得到根本不按REF类型,通话 GetElementType()

An out parameter is "by ref" - so you'll find pInfo.ParameterType.IsByRef returns true. To get the underlying not-by-ref type, call GetElementType():

Type realType = pInfo.ParameterType.GetElementType();

(您应该只有这样做,如果它的的由参,当然,这适用于 REF 参数了。)

(You should only do that if it is by ref, of course. This applies for ref parameters too.)

这篇关于.NET反思 - 如何获得"真正的"从出信息参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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