我希望使用字符串值创建一个类的实例。 根据我在这里读到的内容:Activator.CreateInstance Method (String, String)它应该有效!
public class Foo
{
public string prop01 { get; set; }
public int prop02 { get; set; }
}
//var assName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var assName = System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName;
var foo = Activator.CreateInstance(assName, "Foo");
为什么要赢得这项工作? 我收到以下错误:
{"无法加载类型' Foo'从assembly'组装名称, Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'。":" Foo"}
答案 0 :(得分:4)
您应该使用完整限定类型名称,而不是简单类型名称,包括整个名称空间。
像这样:
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CustomList customList = new CustomList(TrainingProgrammes.this, listProgrms, reference_IDs, programStatus, _tierLevel, _tierIndexValue, programIDS);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (programStatus.get(i).equals("Subscribed")) {
System.out.println("Program id is trianing programme new : " + programIDS.get(i) + " CLIENT_ID " + _clientID);
Intent nextScreen2 = new Intent(getApplicationContext(), TaskList.class);
nextScreen2.putExtra("EMAIL_ID", _loginID);
nextScreen2.putExtra("PROGRAMME_ID", programIDS.get(i));
nextScreen2.putExtra("CLIENT_ID", _clientID);
// nextScreen2.putExtra("PROGRAMME_STATUS", programStatus.get(i));
startActivity(nextScreen2);
}
}
});
}
正如MSDN所说:
首选类型的完全限定名称。
答案 1 :(得分:3)
使用完全限定名称,如已提议的那样:
var foo = Activator.CreateInstance(assName, "FooNamespace.Foo");
或者按名称获取类型:
var type = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
.First(x=>x.Name=="Foo");
var foo = Activator.CreateInstance(type);
更简单的是直接使用你的Foo类:
var foo = Activator.CreateInstance(typeof(Foo));