Invoking static method by type name

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;
}
}
 
J

Jon Skeet [C# MVP]

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.
 
A

Andrus

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;

}
}
 
J

Jon Skeet [C# MVP]

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.
 

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

Top