This should be simple but I can't find anywhere that tells me how to do this. I've got a class, it's in the same dll as the one I am using to do this.
All I want to do is something like.
thing.InstanceClass("ClassName");
I would like to do this without doing:
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");
And that is because the classes I would like to instance using reflection are in the same assembly.
Type instanceType = Type.GetType("SomeNamespace.SomeType");
object instance = Activator.CreateInstance(instanceType);
You can resolve it through Type.GetType(...)
if the assembly is already loaded into the AppDomain.
If you need the assembly you can use Assembly.GetEntryAssembly
, or possibly typeof(SomeType).Assembly
where SomeType
is in your target assembly.
我相信System.Activator.CreateInstance是您寻求的框架方法。
If it's a known (referenced, not COM etc.) type within your project, then the best way is to use the strongly-typed CreateInstance
function:
MyClass instance = Activator.CreateInstance<MyClass>();
This will save much of performance cost since there is no boxing/unboxing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.