C# 通用(即<;T>;)web用户控件的语法
假设我制作了一个web控件,如下所示:C# 通用(即<;T>;)web用户控件的语法,c#,asp.net,generics,.net-3.5,C#,Asp.net,Generics,.net 3.5,假设我制作了一个web控件,如下所示: public class TestControl<T> : WebControl { ... } 公共类TestControl:WebControl { ... } 是否有任何方法可以将该控件放置在.aspx页面上,而不必通过代码进行操作?我真的很想做一些事情,比如: <controls:TestControl<int> runat="server" /> 但据我所知,我无法传入泛型参数。我试着在网上搜
public class TestControl<T> : WebControl
{
...
}
公共类TestControl:WebControl
{
...
}
是否有任何方法可以将该控件放置在.aspx页面上,而不必通过代码进行操作?我真的很想做一些事情,比如:
<controls:TestControl<int> runat="server" />
但据我所知,我无法传入泛型参数。我试着在网上搜索并找到了这个,这似乎正是我想要的,但似乎没有人能理解这个家伙想要什么,我在StackOverflow上也找不到类似的东西。没有。没有办法做到这一点。没有。您最好的选择可能是使用它作为基础,并从中派生出更直接的控件,例如
TestIntControl
、TestStringControl
等等。我知道这违背了纯泛型的目的,但你没有其他选择。然后,您可以在需要显式标记的地方使用这些类型,并且在更动态的页面中仍然具有基础类型的灵活性。您只需将泛型类型抽象,然后继承一个具体类型,然后将其放在页面上即可。一方面,这是更多的代码,但它也允许您通过调用基本构造函数来自定义类型
public abstract class MyGenericControl<T> : WebControl {
...
public T SomeStronglyTypedProperty { get; set; }
protected MyGenericControl(...) {
...
}
...
}
public sealed class MyConcreteControl : MyGenericControl<SomeType> {
public MyConcreteControl()
: base(
...
) {
}
}
即使在.net 4/4.5/等中,也可能存在不存在的副本。?我一直坚持3.5:(不,我从来没有需要做这样的事情。谢谢,但为什么不呢?似乎是一件非常有用和有效的事情。你问我为什么我从来没有需要过一个不存在的特定功能?想想看。@GrantThomas:我同意在这种情况下它是次要的,但实际上你在评论中回答了你的问题(强类型的东西)。这只是另一种可能将运行时异常(由愚蠢的错误引起)转化为编译时异常的东西。
<%@ Page ... %>
<%@ Register assembly="MyAssembly" namespace="MyNamespace" tagPrefix="abc" %>
<asp:Content ...>
<abc:MyConcreteControl id="myConcreteControl" runat="server" />
</asp:Content>
...
SomeType value = GetAValue();
myConcreteControl.SomeStronglyTypedProperty = value;
...