sun*_*itw 2 .net c# reflection
我正在创建一个Windows应用程序,用户从组合框中选择一个类型.根据选择,使用反射我想创建相应类型的实例并调用其方法之一.我想要创建的类型也在与sperate类相同的Windows应用程序中定义.但是我收到标题中提到的错误.继承我的代码.
Form1代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
cbLogs.SelectedIndex = 0;
}
private void btnProcess_Click(object sender, EventArgs e)
{
lblMessage.Text = "";
lblResult.Text = "";
if (cbLogs.SelectedIndex <= 0)
{
lblMessage.Text = "Please select Log to be processed";
cbLogs.Focus();
return;
}
Assembly currAss = System.Reflection.Assembly.GetExecutingAssembly();
//I get above error on below line.
object obj = Activator.CreateInstance(currAss.FullName,"SustainabilityXpress ");
Type type = obj.GetType();
object result = type.InvokeMember("process",
BindingFlags.Default | BindingFlags.InvokeMethod,
null, obj, null);
lblResult.Text = result.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
ILogBase接口:
interface ILogBase
{
string process();
}
Run Code Online (Sandbox Code Playgroud)
实现ILogBase的SustainabilityXpress类:
public class SustainabilityXpress: ILogBase
{
string LogName = "SUSTAINABILITYXPRESS";
public string process()
{
return "Sustainabilityxpress";
}
}
Run Code Online (Sandbox Code Playgroud)
一定要正确命名SustainabilityXpress类 - 你不是想伪装它的命名空间吗?(例如,"Name.Space.SustainabilityXpress").
另外,检查Activator.CreateInstance以确保满足所有要求.
并且,正如@Grzenio指出的那样,名称中可能存在拼写错误SustainabilityXpress.
| 归档时间: |
|
| 查看次数: |
10016 次 |
| 最近记录: |