Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

reflection - How do I create an instance from a string in C#?

I'm reading information from an XML which contains the type of an object that I need to instantiate along with it's constructor parameters.

The object type is actually in another project, within a sibling namespace. (I need to create a Company.Project2.Type within Company.Project1 class.)

I found this question, but it doesn't handle the constructor parameters or the fact that it's in another namespace.

How can I do this?

Edit: The assembly name and default namespace wasn't set correctly in the project properties.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • You need to specify the full type name to Type.GetType(), including namespace, e.g. "Company.Project2.Type"
  • If the type isn't in the same assembly (or mscorlib), you need to give the assembly name too, including version information if it's strongly typed. For example, for a non-strongly typed assembly Company.Project2.dll, you might specify "Company.Project2.Type, Company.Project2".
  • To call a constructor with parameters you can call Activator.CreateInstance(Type, Object[]) or get the exact constructor you want with Type.GetConstructor() and then call ConstructorInfo.Invoke().

If that doesn't help, please give more information.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...