从方法返回一个类名,用它来强制转换

时间:2014-12-20 07:04:51

标签: c# asp.net webforms

我使用FindControl来查找动态控件,但是我无法获得将其投射到的类型。

首先,这些代码甚至不会像这样进行编译,因为在ReturnCastType方法的return语句中它表示" Class name在此时无效"。

我已尝试使用返回关键字“关键字”,“动态”,“对象”和“控件”,并且无法接受我尝试在此处执行的操作。

foreach (var component in controls)
{
        if (component.Section == "Plan")
        {
            string controlName = GetPrefixAndId(component); 
            var castType = ReturnCastType(component);    
            var control = planPanel.FindControl(controlName) as castType; //i want to specify type to cast here

        }
}


private static dynamic ReturnCastType(CustomExamComponent component)
        {
            if (component.ComponentType == "Textbox")
            {
                return TextBox;
            }
            if (component.ComponentType == "Dropdown")
            {
                return DropDownList;
            }
            if (component.ComponentType == "Checkbox")
            {
                return CheckBox;
            }
            return null;
        }

2 个答案:

答案 0 :(得分:1)

当你需要在运行时动态解决问题时,编译时类型无法帮助你。幸运的是Dynamic可供救援。

foreach (var component in controls)
{
    if (component.Section == "Plan")
    {
        string controlName = GetPrefixAndId(component); 
        dynamic control = planPanel.FindControl(controlName);//Note the dynamic keyword
        string controltext = control.Text;//Will be resolved dynamically
    }
}

有一点需要注意,如果您尝试使用的属性/方法在动态成员中不存在,则此代码可能会在运行时失败。否则,它应该工作。

答案 1 :(得分:0)

为什么从dynamic返回ReturnCastType(您认为它应该是什么)?只需返回类似这样的类型:

private static Type ReturnCastType(CustomExamComponent component)
        {
            if (component.ComponentType == "Textbox")
            {
                return typeof(TextBox);
            }
            if (component.ComponentType == "Dropdown")
            {
                return typeof(DropDownList);
            }
            if (component.ComponentType == "Checkbox")
            {
                return typeof(CheckBox);
            }

            throw new NotSupportedException();
        }

哦,如果你不在调用方法中检查它,你不应该在这里返回null。相反,你应该立即失败。

相关问题