开发者

New object from type? Specifically a resx file. I want a different resx at runtime

I'm trying to use browser specific resx files in some automation tests. I'm stuck at the point where I wish to instansiate the type. Can anyone point me in the right direction? I have tried activator.createInstance etc... with no luck.

 public class WebAiiBaseTest : BaseTest
{
    private readonly IDictionary<BrowserType, Type> resxMapper = new Dictionary<BrowserType, Type>{
                                                                {BrowserType.Chrome, typeof(Chrome)}
                                                                , {BrowserType.Safari, typeof(Safari)}
                                                                , {BrowserType.FireFox, typeof(Firefox)}
                                                                , {BrowserType.InternetExplorer, typeof(InternetExplorer)}
                                                            };



    [TestFixtureSetUp]
    public void FixtureSetup()
    {
        Initialize();
        Launcher.LaunchRepairInformation();

    }

    [TearDown]
    public void TestCleanUp()
    {
        Launcher.NavigateToRepairInformation();
    }

    [TestFixtureTearDown]
    public void FixtureCleanup()
    {
        CleanUp();
    }

    protected object BrowserResx
    {
        get { return Activator.CreateInstance(resxMapper[ActiveBrowser.BrowserType]); }

    } 


}

This code returns an instance, but it is of type object. I would like to return a strongly typed instance. I have tried the generic overload for CreateInstance, like this

return Activator.CreateInstance<resxMapper[ActiveBrowser.BrowserType]>(); 

but Visual Studio does not like this syntax. What am I d开发者_运维问答oing wrong here? Thanks for any tips or advice.

Cheers,

~ck in San Diego


your code is not correctly spelled, did you try

return Activator.CreateInstance(resxMapper[ActiveBrowser.BrowserType]); ?


I'm still not getting exactly what you're trying to do but here are the only things I can think of, I'm not sure the comment thread is getting any more clear.

public interface IBrowser
{
}
public class Chrome: IBrowser
{
}
... 

protected IBrowser BrowserResx
{
    get { return (IBrowser)Activator.CreateInstance(resxMapper[ActiveBrowser.BrowserType]); }

} 

Alternatively:

protected T BrowserResx<T> where T: IBrowser
{
        get { return (T)Activator.CreateInstance(resxMapper[ActiveBrowser.BrowserType]); }
}

.. if your class was designed as a generic. If there's no base class for the browser types, or interface, then there's no way to return something more strongly typed: they only share "object" in common.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜