c# - 使用 GetType() 和反射进行转换 [英] c# - Cast with GetType() and reflection

查看:74
本文介绍了c# - 使用 GetType() 和反射进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此在使用 this 教程我有几个从 BasePageElementMap 派生的页面.

So after implemented Page Object Pattern using this tutorial i have several Pages that derived from BasePageElementMap.

我想处理一些操作所以我有这个类:

And i want to handle some operation so i have this class:

public class DownloadAttachmentsHandler
    {
        public DownloadAttachmentsHandler(BasePageElementMap basePageElementMap)
        {
            Type type = basePageElementMap.GetType();            
        }
    }

BasePageElementMap 派生的每个 Pages 都有这个 html 元素,这些元素位于从 BasePageElementMap 派生的类中从这个 Page 我有这个 Map 对象,它包含我正在使用的所有 HTML 元素.

Every Pages that derived from BasePageElementMap have this html elements that locate inside its class that derived from BasePageElementMap and from this Page i have this Map object that contains all my HTML elements that i am using.

public class YahooEmailPage: BasePage<YahooEmailPageElementMap, YahooEmailPageValidator>...

所以如果我这样调用这个函数:

so in case i am call this function like this:

UploadAttachmentsHandler att = new UploadAttachmentsHandler(new YahooEmailPage().Map);

我想从我的 DownloadAttachmentsHandler 方法将其转换为 YahooEmailPage.

I want to cast this into YahooEmailPage from my DownloadAttachmentsHandler method.

所以目前我有这个 type 对象,我怎样才能把它放到 YahooEmailPage 中?

So currently i have this type object, how can i case it into YahooEmailPage ?

推荐答案

如果我理解正确,您需要以下内容:

If I understood correctly, you want the following:

public class DownloadAttachmentsHandler
{
    public static object Cast(object obj, Type t)
    { 
        try
        {
            var param = Expression.Parameter(obj.GetType());
            return Expression.Lambda(Expression.Convert(param, t), param)
                 .Compile().DynamicInvoke(obj);
        }
        catch (TargetInvocationException ex)
        {
             throw ex.InnerException;
        }         
    }


    public DownloadAttachmentsHandler(BasePageElementMap basePageElementMap)
    {
        Type type = basePageElementMap.GetType();
        dynamic foo = Cast(basePageElementMap, type);
    }
}

基于 this balage 的回答.

Based on this answer by balage.

例如,假设 GetType() 返回类型 bar.您必须创建一个这样的方法:

For the example, lets assume that GetType() returns the type bar. You will have to create a method like this one:

public static void UseDynamic(bar input)
{
    // Stuff
}

然后做

public DownloadAttachmentsHandler(BasePageElementMap basePageElementMap)
{
    Type type = basePageElementMap.GetType();
    dynamic foo = Cast(basePageElementMap, type);
    UseDynamic(foo);
}

您可以使用重载来避免编写许多 if 或一个开关.但是,无论采用哪种方法,都必须为每种可能的类型创建一个方法.

You can use overloads to avoid having to write many ifs or a switch. However, whichever approach you take, you will have to create a method for each possible type.

这篇关于c# - 使用 GetType() 和反射进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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