Base classes for Page and UserControl:
public class MyWebPage : System.Web.UI.Page { }
public class MyUserControl : System.Web.UI.UserControl { }
Helper that either of them might use:
void SetSessionValue<T>(string key, T value) { Session[key] = value; }
How can I achieve something like the following?
public class WebObject // can't inherit from both Page and UserControl {
protected void SetSessionValue<T>(string key, T value) {
Session[key] = value;
}
}
public class MyWebPage : WebObject { }
public class MyUserControl : WebObject { }
Update: I got excited for a second hoping I could solve it this way, but alas it doesn't compile.
public class WebObject<T> : T
{
}
public class MyWebPage : WebObject<System.Web.UI.Page>
{
}
You can't. Not easily anyway. I'd recommend just creating a base class for pages and user controls, and duplicating the common code in both. Since user controls are contained in pages, you can also delegate methods in the base user control class to the base page class simply by casting the Page
property to your own type:
// Code in the MyUserControlBase class
public int SomeCommonMethod() {
return ((MyBasePageType)this.Page).SomeCommonMethod();
}
You can also make your life miserable by creating an interface implemented by both base classes and using DI to intercept method and property accessor calls, which would then be routed to some kind of common surrogate class that actually provides the implementation. I probably wouldn't go there :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With