大家好, 关于这个主题有一些问题和答案,但是,没有一个能解决我的问题。我是一个关于c#的新手。 我是一个班级并且有一个字符串值。如果字符串值与类名相同,则从该类创建新对象。 字符串值是基本 和班级名称是基本 我知道解决方案是Assembly.CreateInstance,但它总是为空,无法成功创建任何实例。 名称:TTT Publickeytoken = null CodeBase:TTT.exe文件的路径 我尝试过:
命名空间TTT { public class Basic { public string Id {get;组; public int SourceSystem {get;组; } } 公共类Message_Tag_Info { public string Id {get;组; } 公共字符串ClassCode {get;组; } 公共字符串ClassName {get;组; } } class程序 { static void Main(string [] args) { Message_Tag_Info message = new Message_Tag_Info() ; string tmp =Basic; message.ClassName = tmp; 类型t = Type.GetType(TTT。+ message.ClassName); Assembly assem = Assembly.GetAssembly(t); Console.WriteLine(Name:{0},assem.FullName); Console.WriteLine(CodeBase:{0},assem.CodeBase); var obj = Assembly.GetExecutingAssembly()。CreateInstance(message.ClassName); Console.ReadLine(); } } }解决方案
你试过吗? Activator.CreateInstance,下面是几个例子,我希望这有帮助 c# - 创建一个类名的对象实例,其名称在字符串变量中 - Stack Overflow c# - 从字符串创建类的实例 - Stack Overflow
你只是在基本上做CreateInstance而且这还不足以反映出你的意思是什么类,它需要全名TTT.Basic 下面我使用t.FullName代替 var obj = Assembly.GetExecutingAssembly( ).CreateInstance(t.FullName);
Hi all, There are some questions and answers about this topic but, none of them solve my issue. I am a quite new about c#. I've a class and had a string value. If the string value same with class name, create new object from that class. string value is "Basic" and class name is "Basic" I know the solution is Assembly.CreateInstance but it always gets null , could not success to create any instance. Name:TTT Publickeytoken=null CodeBase: path to TTT.exe file What I have tried:
namespace TTT { public class Basic { public string Id { get; set; } public int SourceSystem { get; set; } } public class Message_Tag_Info { public string Id { get; set; } public string ClassCode { get; set; } public string ClassName { get; set; } } class Program { static void Main(string[] args) { Message_Tag_Info message = new Message_Tag_Info(); string tmp = "Basic"; message.ClassName = tmp; Type t = Type.GetType("TTT."+message.ClassName); Assembly assem = Assembly.GetAssembly(t); Console.WriteLine("Name: {0}", assem.FullName); Console.WriteLine("CodeBase: {0}", assem.CodeBase); var obj = Assembly.GetExecutingAssembly().CreateInstance(message.ClassName); Console.ReadLine(); } } } 解决方案 Have you tried Activator.CreateInstance, below are few examples, I hope this helps c# - Create object instance of a class having its name in string variable - Stack Overflow c# - Create an instance of a class from a string - Stack OverflowYou're doing CreateInstance on just "Basic" and that's not enough for reflection to work out what class you mean, it needs the full name of TTT.Basic Below I use t.FullName instead var obj = Assembly.GetExecutingAssembly().CreateInstance(t.FullName);更多推荐
从字符串创建对象
发布评论