0

我使用 C# 创建了一个 Web 窗体用户控件。我已更改用户控件的 .cs 文件(代码和设计器)以允许任何类型。

public partial class MyGenericControl<T> : System.Web.UI.UserControl
{
}

现在我正在尝试在像这样的 ASP.NET 表单中使用它

<uc1:MyGenericControl runat="server" id="MyGenericControl1"  />

但我不知道如何将我需要的类型发送到控件。

感谢您对此问题的任何建议或帮助。

4

1 回答 1

0

我会将我的回复放在评论中,因为我还没有答案,但我没有 50 个代表,所以我无法发表评论。

这是处理用户控件的一种非常有趣的方式。我的问题是,你想用这个来完成什么?我们需要知道,因为您的解决方案可能不涉及拥有接受任何类型的用户控件 - 就像 Stilgar 说的那样。

您可以使用枚举器/属性组合来完成此操作。这就是我想出的:

<uc1:MyGenericControl runat="server" id="MyGenericControl1" myControlType="DropDownList"  />

public partial class MyGenericControl<T> : System.Web.UI.UserControl
{
    public enum ucType : ushort
    {
        DropDownList = 1,
        TextBox,
        Button,
        Etc
    }

    private ucType _controlType;

    public ucType myControlType
    {
        get{return _controlType;}
        set{ T = value; } /* Somehow set T to the value set in ASP.  
    In this example, value would be "1" so it would throw an error, but you get the idea. */
    }
}

这比完整的答案更具启发性和发人深省,因为我不知道是否甚至可以动态设置类类型(尤其是您当前正在使用的类类型)。有一种Convert.ChangeType方法,但我认为这在这里行不通。

于 2014-09-22T16:44:30.363 回答