开发者

Create a parameterized base web page in asp.net

开发者 https://www.devze.com 2022-12-17 11:58 出处:网络
I have a class hierarchy where IObject is the base class for product and customer. I want to define a base page in asp.net which shoud contain generic code. The generic page displays the name of the o

I have a class hierarchy where IObject is the base class for product and customer. I want to define a base page in asp.net which shoud contain generic code. The generic page displays the name of the object and allows user to delete the object by asking for confirmation. The page has to be written against the IObject 开发者_运维问答type. I am trying to define a base page in a below manner but it is giving a compile time error:

public class BaseDeletePage<T> : System.Web.UI.Page
   where T:IObject
{
}

It is giving the following compilation error: "Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl)"

The generic problem statement is: How to define a parameterized web page class, which could be used by other pages as a base class.


Since you already have an IObject^ interface defined for products and customers, I would recommend simply passing that via a property, instead of giving the class a type parameter.

So that would be:

public class BaseDeletePage : Page {
    public IObject ObjectToBeDeleted { get; set; }
}

^ And may I suggest a different interface name? IObject is a bit misleading.

[edit] What Joel Coehoorn wrote is correct. The root problem is that you can't instantiate a BaseDeletePage, because it doesn't know what T is. My answer here is that you don't need a type parameter at all. You simply need a base class that can handle something giving it a reference to the object to be deleted, and that can be done via a property.


You can build generic base page classes with asp.net, but you cannot instantiate them directly. You must give them a specific (specialized) type. So the code you posted is legal, but you cannot connect directly to an aspx file in the normal way. To use it, what I would normally do is something like this:

public class MyDeletePage : BaseDeletePage<IObject>
{
}

Remember, an asp.net page is realized by creating instances of your class. Just like you can't create an instance of a List<T> without telling the compiler what "T" is, you can't use your generic asp.net page until you tell the compiler (and not just the runtime) what your specialized type will be for that page.


I assume you have an ASPX file mapped to this base page? There's something wrong with your inherits statement.

<%@ Page Inherits="BaseDelegatePage<IObject>" %>
0

精彩评论

暂无评论...
验证码 换一张
取 消