【问题标题】:Cannot implicitly Convert Type string to无法将类型字符串隐式转换为
【发布时间】:2011-03-08 17:49:45
【问题描述】:

这是我正在使用的代码..

使用 PWServiceProxy

PortfolioQueryOptions Query = new PortfolioQueryOptions();
Query.PortfolioTypes = "Funded";

我收到一个错误,例如

无法将类型字符串隐式转换为 PWServiceProxy.PortfolioTypes。

【问题讨论】:

    标签: c# .net type-conversion


    【解决方案1】:

    似乎Query.PortfolioTypesPWServiceProxy.PortfolioTypes 的类型,即enum

    所以你需要

    Query.PortfolioTypes = PortfolioTypes.Funded;
    

    string str = "Funded"; // or something else
    PortfolioTypes pt;
    if (Enum.TryParse(str, out pt))
        Query.PortfolioTypes = pt;
    else
        throw new Exception("Can't parse input as PortfolioTypes");
    

    【讨论】:

    • +1 在所描述的场景中当然更好 - 只有当您使用从某个地方获得的字符串卡住时才应该进行解析
    • 那行不通。因为我需要将字符串传递给 Query.PortfolioTypes
    • @Peddireddy: PortfolioTypes 显然不是 string 类型 - 如果不是 enum,请与我们分享类型
    • Portfolio Type 是一个来自 PWServiceProxy 的对象。
    • @Peddireddy:它是什么类型的?试试value.GetType().ToString()。还是object
    【解决方案2】:

    假设PortfolioTypesenum,名称为YourEnumType,试试这个:

    Query.PortfolioTypes = (YourEnumType) Enum.Parse(typeof(YourEnumType), "Funded", true);
    

    【讨论】:

    • TrParse() 更快且类型安全
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2014-05-15
    • 2014-02-04
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多