通用(即)Web用户控件的语法

假设我已经制作了如下网页控件:

public class TestControl : WebControl { ... } 

有没有办法将该控件放在.aspx页面而不必通过代码执行? 我真的希望能够做到这样的事情:

 <controls:TestControl runat="server" /> 

但据我所知,我无法传递generics参数。 我已经尝试在网上搜索并发现这个http://forums.asp.net/t/1309629.aspx ,这看起来正是我所追求的,但似乎没有人能理解那个人想要的东西,并且我在StackOverflow上找不到类似的东西。

不,没有办法做到这一点。

不。 你最好的选择可能是使用它作为基础并从中获得更多的直接控制,例如TestIntControlTestStringControl和诸如此类的东西。 我知道这违背了纯通用主义的目的,但你没有其他选择。 然后,您可以在需要显式标记的位置使用这些类型,并且在更多动态页面中仍然具有基础类型的灵活性。

您可以将generics类型设为abstract,并inheritance可以放在页面上的具体类型。 一方面,这是更多的代码,但它也允许您通过调用基础构造函数来自定义类型。

 public abstract class MyGenericControl : WebControl { ... public T SomeStronglyTypedProperty { get; set; } protected MyGenericControl(...) { ... } ... } public sealed class MyConcreteControl : MyGenericControl { public MyConcreteControl() : base( ... ) { } } 

在你的标记中:

 <%@ Page ... %> <%@ Register assembly="MyAssembly" namespace="MyNamespace" tagPrefix="abc" %>    

然后在你的代码后面:

 ... SomeType value = GetAValue(); myConcreteControl.SomeStronglyTypedProperty = value; ...