generic - getType for cast - c# .Net2 aspx

  • Thread starter Thread starter Steph
  • Start date Start date
S

Steph

hello,
i want to find the type from a generic... like :
public static john<T>(object obj, T myControl)
{
((myControl.getType())myControl).OnClientClick ="code";
}

because my generic var can be a Button, LinkButton, ... with "OnClientClick
" event.
and i dont want use :

public static john(object obj, LinkButton myControl)
{
myControl.OnClientClick ="code";
}
public static john(object obj, Button myControl)
{
Button.OnClientClick ="code";
}

thx
 
Normally, that wouldn't be a generics question, but rather a base-class
/ interface question.

However, in this case the OnClientClick property isn't exposed in a
base-class / interface; one solution here would be reflection;
*however* since there are only 3 classes (Button, ImageButton and
LinkButton) with this property, I would actually recommend the
overloaded form that you have written. It will be a lot faster.

Marc
 
i code that :

public static bool john<T>(T myControl)
{
switch(myControl.GetType().Name)
{
case "Button":
case "ImageButton":
case "LinkButton":
myControl.getType().GetProperty("OnClientClick").SetValue(myControl,"code",null);
return true;
}
return false;
}
 
As Dale and myself already observed : you aren't using the generic, so
don't code it as though you are. Generics cannot solve this problem.
Reflection will work, but will be the slowest of the three options.
Overloading will be the fastest, but requires the object to be typed
when calling. If all you know is that it is a control (or object,
even), then Dale's type-testing is your best bet.

Marc
 
Hi,
"Why not just do this:" : because my "code" section is "hard" and i dont
want repeat it three time :
public static bool createLink<T>(T myControl, string message, string action,
string code)
{
switch (myControl.GetType().Name)
{
case "LinkButton":
case "Button":
case "ImageButton":
IAction ia = ((IAction)((myControl as
Control).Parent.NamingContainer));
myControl.GetType().GetProperty("OnClientClick").SetValue(myControl,
"if(confirm('"+message+"')){document.getElementById('" + ia._ActionID +
"').value='" + action + "';document.getElementById('" + ia._ValueID +
"').value='" + code + "'; }else return false;", null);
return true;
}
return false;
}

generic, reflection, ..., no importance... i want just no repeat my code...
and i wnt take take the best/good way to do it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top