使用C#.net将字符串分配给Type时出现问题 [英] Problem getting while string assign to Type using C#.net
问题描述
public static Form getFrom()
{
string formname=Assembly.GetEntryAssembly().GetName().Name+"."+"AddForm";
//actually formname contain this string "DynamicProject.AddForm" but tp shows null value
Type tp=Type.GetType(formname);
baseForm=(Form)Activator.CreateInstance(tp);
///here shows null value does not return
return baseForm;
}
我已经尝试了很多次,但是却出现了同样的错误,请帮助我
I have tried so many times,But but it same error, Please Help Me
推荐答案
var newForm=(Form)Activator.CreateInstance(null, "aFrmInCurrntCntxt").Unwrap();
newForm.Text = "some new form";
newForm.Show();
在Activator.CreateInstance的此两字符串参数变体中,如果第一个参数字符串"AssemblyName"为"null:",则MS表示:正在搜索执行程序集. "
请注意,CreateInstance的这种形式返回必须展开的"System.Runtime.Remoting.ObjectHandle".
此技术不需要反射.
在简单的WinForms应用程序中经过测试和验证.
希望这会有所帮助.
In this two-string-parameter variant of Activator.CreateInstance, if the first parameter string, "AssemblyName," is ''null:'' MS says: "the executing assembly is searched."
Note this flavour of CreateInstance returns a "System.Runtime.Remoting.ObjectHandle" that must be unwrapped.
This technique does not require Reflection.
Tested and verified in a simple WinForms app.
Hope this helps.
为什么不使用 FindTypes [ ^ ]直接?
Why not use FindTypes[^] directly?
这篇关于使用C#.net将字符串分配给Type时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!