代码之家  ›  专栏  ›  技术社区  ›  KenF

如何在C#中动态强制转换并返回属性

  •  0
  • KenF  · 技术社区  · 16 年前

    我已经读过关于这个话题的文章,但找不到合适的解决方案。

    我正在处理一个下拉列表,它接受一个枚举并使用它来填充自己。我找到一个VB.NET版一个。在移植过程中,我发现它使用DirectCast()在返回SelectedValue时设置类型。

    http://jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx

    关键是,控件

    Type _enumType; //gets set when the datasource is set and is the type of the specific enum
    

    这个 SelectedValue 属性看起来像(记住,它不起作用):

        public Enum SelectedValue  //Shadows Property
        {
            get
            {
                // Get the value from the request to allow for disabled viewstate
                string RequestValue = this.Page.Request.Params[this.UniqueID];
    
                return Enum.Parse(_enumType, RequestValue, true) as _enumType;
            }
            set
            {
                base.SelectedValue = value.ToString();
            }
        }
    

    DirectCast 不需要,因为在每个示例中,它们都静态地定义了类型。

    这里不是这样的。作为控件的程序员,我不知道类型。所以,我不能投。另外,下面的行示例不会编译,因为c#casting不接受变量。而VB CType 直播 可以接受类型T作为函数参数:

    return Enum.Parse(_enumType, RequestValue, true);
    

    return Enum.Parse(_enumType, RequestValue, true) as _enumType;
    

    return  (_enumType)Enum.Parse(_enumType, RequestValue, true) ;
    

    return Convert.ChangeType(Enum.Parse(_enumType, RequestValue, true), _enumType);
    

    return CastTo<_enumType>(Enum.Parse(_enumType, RequestValue, true));
    

    有什么解决办法吗?.NET3.5最好的解决方法是什么?

    3 回复  |  直到 16 年前
        1
  •  4
  •   Jon Skeet    16 年前

    你不需要选择正确的类型。。。您只需要强制转换到枚举。这就是声明的属性类型,毕竟:

    return (Enum) Enum.Parse(_enumType, RequestValue, true);
    

    Enum.Parse 老实说,并没有声明返回枚举本身。它不可能是任何其他类型。)

        2
  •  1
  •   earlNameless    16 年前
    • 仿制药
    • 返回(枚举)枚举解析(\u enumType,RequestValue,true);

    第二种方法之所以有效,是因为不需要将值作为给定类型返回,只需要将值作为类型返回即可 即使它是下面的实际枚举。

        3
  •  0
  •   Samuel Neff    16 年前

    处理它的最佳.NET2.0/3.5方法是使用泛型。