Compute null listing with reflection?

Given the null action:

var result = MyMethod( (Foo) null );

      

Can this additional information be used inside a method with reflection?

EDIT:
The method signature looks something like this:

object MyMethod( params object[] args )
{
  // here I would like to see that args[0] is (was) of type Foo
}

      

+1


a source to share


2 answers


Ah ... you edited ...

I suspect the closest you get to generics is:

object MyMethod<T>( params T[] args ) {...}

      

(and see typeof(T)

)

But that means everyone is the args

same. Besides; no. Every zero is the same as every other ( Nullable<T>

aside) and you cannot specify the type of the variable.




Original answer:

Do you mean overload resolution?

object result = someType.GetMethod("MyMethod",
        new Type[] { typeof(Foo) })
        .Invoke(someInstance, new object[] { null });

      

(where someInstance

is null

for static methods, and someType

is that Type

which has the method MyMethod

)

+2


a source


Short answer: No

I assume you have something like this:

class Foo : Bar{}

      

Since you have:

object MyMethod(param object[] values);

      



There is no way to do this. You can use the null object pattern to accomplish this:

class Foo : Bar
{
 public static readonly Foo Null=new Foo();
}

      

and then call with Foo.Null instead of null. Then MyMethod can check the static instance and act accordingly:

object MyMethod(param object[] values
{
 if(values[0]==Foo.Null) ......
}

      

+1


a source







All Articles