枚举不能将类型字符串隐式转换为枚举

Enum cannot implicitly convert type string to enum

我在枚举中有一个 URL 的列表。我想将枚举值作为参数传递给我的方法,并使用它浏览到使用 Selenium Web 驱动程序的 URL。

Error CS0029 Cannot implicitly convert type 'string' to 'automation.Enums.UrlEnums.Url' automation F:\Projects\C#\automation\Helpers\NavigateHelper.cs 22 Active

我的代码片段是:

public class UrlEnums
{
    public enum Url
    {
        [Description("https://www.companysite1.com")] 
        company1,
        [Description("https://www.companysite2.com")] 
        company2
    }
}

public void NavigateTo(UrlEnums.Url url)
{
    switch (url)
    {
        case "Thriller":
            Driver.Navigate().GoToUrl(url);
            //Driver.Navigate().GoToUrl("https://www.companysite1.com");
        break;

        case "Comedy":
            Driver.Navigate().GoToUrl(url);
        break;
    }
}

如何使用枚举作为参数传递并转到URL? 此枚举列表将会增长,很快就会有更多 URL。

我的 SpecFlow 场景是:

Feature: WelcomePage
    In order to view the film categories
    As a user I should be able to click on a category
    I should see the welcome page for the selected category

@smoke 
Scenario Outline: NavigateToFilmCategory
    Given I navigate to <Category> page
    Then I should see the welcome page <WelcomePage>

Examples: TestData
| Category    | WelcomePage     |
| Thriller    | Thriller Films  |
| Comedy      | Comedy Films    |
| Action      | Action Films    |
| Adventure   | Adventure Films |

谢谢,

在这种情况下不需要使用switch case,因为你对不同的值执行相同的操作。如果您使用反射来查找 url 值,则可以对该特定的 url 执行操作(导航)。

希望对您的问题有所帮助。

public enum UrlEnum
{
    [Description("https://www.companysite1.com")]
    company1,

    [Description("https://www.companysite2.com")]
    company2
}

public void NavigateTo(UrlEnum url)
{
    MemberInfo info = typeof(UrlEnum).GetMember(url.ToString()).First();
    DescriptionAttribute description = info.GetCustomAttribute<DescriptionAttribute>();
    if (description != null)
    {
        //do something like
        Driver.Navigate().GoToUrl(description.Description);
    }
    else
    {
        //do something
    }
}

一个好的解决方案是这样的:

public class UrlEnums
{
    public enum Url
    {
        [Description("https://www.companysite1.com")] 
        company1,
        [Description("https://www.companysite2.com")] 
        company2
    }
}

public void NavigateTo(UrlEnums.Url url)
{

     Driver.Navigate().GoToUrl(GetEnumDescription(url));

}

    public static string GetEnumDescription(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }

The GetEnumerationDescription i found here

这就是您要找的东西吗?