Invoking static method by type name

  • Thread starter Thread starter Andrus
  • Start date Start date
A

Andrus

I know entity class name as string ( e.q. "Customer", "Product")
I need to invoke static method in this entity class.

I tried the following code but got compile error shown in comment.
How to invoke static method when type name is known as string ?

Andrus.



using System.Collections.Generic;
using System;

class TestApplication {

static void Main() {
FindByTypeName("Customer");
FindByTypeName("Product");
}

static object[] FindByTypeName(string typename) {

Type t = Type.GetType(typename);
ActiveRecordBase<object> entity = (ActiveRecordBase<object>)
System.Activator.CreateInstance(t);

// Error: Static member 'ActiveRecordBase<object>.FindAll()' cannot be
// accessed with an instance reference; qualify it with a type name
//instead
return entity.FindAll();

}

}

class Customer : ActiveRecordBase<Customer> {}

class Product : ActiveRecordBase<Product> {}

public class ActiveRecordBase<T> {
public static T[] FindAll() {
// method implementation skipped
return null;
}
}
 
Andrus said:
I know entity class name as string ( e.q. "Customer", "Product")
I need to invoke static method in this entity class.

I tried the following code but got compile error shown in comment.
How to invoke static method when type name is known as string ?

You need to use reflection to get the MethodInfo, using Type.GetMethod.
Then call MethodInfo.Invoke.
 
You need to use reflection to get the MethodInfo, using Type.GetMethod.
Then call MethodInfo.Invoke.

Jon,

thank you very much.
I tried this but got assertion failed error.
What I'm doing wrong ?

using System.Collections.Generic;
using System;
using System.Windows.Forms;

class TestApplication {

static void Main() {

MessageBox.Show(FindByTypeName("Customer").ToString());

}

static object[] FindByTypeName(string typename) {

Type t = Type.GetType(typename);

System.Reflection.MethodInfo mi = t.GetMethod("FindAll",
System.Reflection.BindingFlags.Static);

System.Diagnostics.Debug.Assert(mi != null);

object[] entity = (object[])mi.Invoke(null, null);

return entity;

}

}

class Customer : ActiveRecordBase<Customer> {

}

public class ActiveRecordBase<T> {

public static T[] FindAll() {

// method implementation skipped

return null;

}
}
 
Andrus said:
thank you very much.
I tried this but got assertion failed error.
What I'm doing wrong ?

The method you're looking for is in the type up the hierarchy chain, so
you need the FlattenHierarchy flag. If you include
"using System.Reflection;" at the top of the file, use the binding
flags of:

BindingFlags.Static |
BindingFlags.Public |
BindingFlags.FlattenHierarchy

and all will be well.
 
Back
Top