我正在尝试使用以下代码动态地从另一个程序集中调用它的派生类的基类静态方法:
Assembly executingAssembly = Assembly.GetExecutingAssembly();
Assembly objectAssembly =
Assembly.Load(executingAssembly.GetReferencedAssemblies().
Where(a => a.Name == "WebDelightBLL").FirstOrDefault());
Type myType = objectAssembly.GetType("WebDelightBLL.Ingredient");
MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public | BindingFlags.Static);
object myInstance = Activator.CreateInstance(myType);
dgvResultsRES.DataSource = myMethod.Invoke(myInstance, null);
Dll中的代码如下:
public class BaseClass<DerivedClass>
{
public static Type MyType()
{
return typeof(DerivedClass);
}
public static string Prefix()
{
return "Sp" + MyType().Name;
}
public static DataTable GetAll()
{
try
{
DataTable dt = GetSP(Connection.connectionString(),
Prefix() + "GetAll", 5);
return dt;
}
catch (Exception)
{
throw;
}
}
}
public class Ingredient : BaseClass<Ingredient>
{
public string SayHello()
{
return "Hello, World!"; //Just to exemplify a point
}
}
但我总是得到“对象引用没有设置为对象的实例”
例如,如果我尝试调用'SayHello()',则不会出现错误。
这甚至可能吗?
更新
通过添加Creep指示的BindingFlags.FlattenHierarchy,它就像一个魅力。工作代码如下:
Type myType = objectAssembly.GetType("WebDelightBLL.Ingredient");
MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public
| BindingFlags.Static | BindingFlags.FlattenHierarchy);
//object myInstance = Activator.CreateInstance(myType); <-- not needed.
dgvResultsRES.DataSource = myMethod.Invoke(null, null);
答案 0 :(得分:1)
由于您的方法在基类中是静态的,因此它不属于其子类 以下代码将起作用:
Type myType = objectAssembly.GetType("WebDelightBLL.BaseClass");
MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public | BindingFlags.Static);
myMethod.Invoke(null, null);
答案 1 :(得分:1)
您正在尝试调用静态方法,因此您无法指定对象的实例(以摆脱&#34;对象引用未设置为对象的实例&#34;错误)。由于此方法没有任何参数,您只需创建一个空参数数组
MethodInfo myMethod = myType.GetMethod("GetAll", BindingFlags.Public | BindingFlags.Static);
// dont need this
//object myInstance = Activator.CreateInstance(myType);
//dgvResultsRES.DataSource = myMethod.Invoke(myInstance, null);
dgvResultsRES.DataSource = myMethod.Invoke(null, new object[0]);