Custom attribute for a method: how to get the method object ?

  • Thread starter Thread starter Oriane
  • Start date Start date
O

Oriane

Hi,

I'm currently a method attribute which is used to check the "validity" of this method against a rule.
I wrote the isValid method, to be used inside the otriginal method:

For instance:
// Following is Csharp code

[ruleAttribute ("rule1")]
private void functionT12 ()
{
if (v.IsValid ()) {
...
}
}

isValid should be called with an method instance, taht is to say that "v" must reference the "functionT12" object.

So question is: how can I create a object reference on the current method ?
Is there something like a "CurrentMethod" property on a class object ?

Oriane
 
Oriane said:
I'm currently a method attribute which is used to check the
"validity" of this method against a rule.
I wrote the isValid method, to be used inside the otriginal method:

For instance:
// Following is Csharp code

[ruleAttribute ("rule1")]
private void functionT12 ()
{
if (v.IsValid ()) {
...
}
}

I am not too sure about the relationship of the [ruleAttribute] to the
function, in your code you don't use it, so I guess it is irrelevant
with respect to your question. Where does v come from?
isValid should be called with an method instance, taht is to say that
"v" must reference the "functionT12" object.

So question is: how can I create a object reference on the current
method ?
Is there something like a "CurrentMethod" property on a class object ?

You can get a 'method instance' using reflection. For example,

class Tester
{
object o;
public Tester(object obj)
{
o = obj;
}
public bool IsValid(string method)
{
MethodInfo mi = o.GetType().GetMethod(method);
// validate the method mi using object o.
return //somevalue;
}
}

private void functionT12 ()
{
Tester v = new Tester(this);
if (v.IsValid ("functionT12")) {
...
}
}

If you don't want to do that, you could use the
System.Diagnostics.StackTrace to get the call stack, then call
GetFrame() to get the previous method in the call stack (ie the method
that called IsValid). This will give you a StackFrame object that has a
GetMethod() method which you can call to get access to the method
object.

Richard
 
Back
Top