Hi Gene,
No, this is not what Generics are used for. A Generic class is a class that
takes one or more type parameters. When a Generic class is compiled, it uses
the type(s) passed to it, and is strongly typed.
What you're talking about is reflection, which is the discovery of
characteristics of a type. From what I gather from your description, the
only thing known about the container Control for your Control is that it is
a Control, which isn't going to tell you anything about whether or not it
has a member defined that is a Method of the description you're looking for.
Therefore, you need to use reflection to find out.
The code you posted is close to the solution, but makes several fatal
assumptions. First, the return value of Type.GetMember() is an array of
System.Reflection.MemberInfo, but you are treating it as if it is a single
value. All you probably need to know is whether or not the Member Method
exists, and what type to cast the container to in order to properly access
the Member. So, what you need to do is first determine the type:
System.Type t = this.Parent.GetType();
You need to store this in order to use it for casting if the Member exists.
Otherwise, you have to call GetType() twice.
Next, check to see whether the Member exists:
if (t.GetMember("MyCustomMethod")) != null
{
t.InvokeMember(("MyCustomMethod", BindingFlags.InvokeMethod, null,
this.Parent, new Object[] {this});
}
--
HTH,
Kevin Spencer
Microsoft MVP
..Net Developer
If you push something hard enough,
it will fall over.
- Fudd's First Law of Opposition
"Gene Vital" <no********@msnew.com> wrote in message
news:%2****************@TK2MSFTNGP09.phx.gbl...
Hi all,
I need some help in understanding how to use Generics. I have a class
based on a user control that can be put on any Container at runtime, I
want to be able to call a method on the parent class without knowing the
type of the parent class, can this be done with C#?
I thought this was what Generics was supposed to be all about but I have
spent the whole day Googling and I can't find a way to do this in C#.
An example would be
public class MyClass : UserControl
{
public void SomethingChanged()
{
// this method is bound to an event somewhere
// call the parent class method, I don't care what type the parent class
is just that is has the MyCustomMethod() method.
if (this.Parent.GetType().GetMember("MyCustomMethod") .GetLength(0) > 0)
this.parent.MyCustomMethod(this)
}
}
thanks for all the help