Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class type by its class name?

namespace Myspace {     public class MyClass     {     } } //This class is in another file.  using Myspace; static void Main(string[] args) {     Regex regexViewModelKey = new Regex(RegularExpr.ViewModelKeyPattern);     string viewModel = regexViewModelKey.Match(match.Value).Value;     //Now, vieModel is a string, and its value is "MyClass". So, I only know the class name, this is why I ask this question.      //Now, I'm only allowed to use the string form of this class name to get its type.     //I have tyied like this, but its no use.     Type t = Type.GetType(viewModel);     //it's return a null.      //Then I tyied another method like this, but there is an exception when calling Assembly.Load     Assembly assembly = Assembly.Load("Myspace");     Type ty = assembly.GetType("Myspace" + viewModel); } 

I hope my question is clear. Can any one help me.THX I'm only allowed to use the string form of this class name to get its type.

thx everyone. I have solved this question by myself like this.

{       Type t = Type.GetType(string.Concat(viewModel, ",", "Myspace")); } 
like image 420
Huan Fu Avatar asked Aug 19 '13 06:08

Huan Fu


People also ask

How to get the typeof a class in c#?

The GetType() method of array class in C# gets the Type of the current instance (Inherited from Object). To get the type. Type tp = value. GetType();

How do I get a className?

The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.


1 Answers

just use the function typeof(). The parameter is just that class name.

Type type = typeof(FIXProtoClientTest); 

MSDN on typeof()

like image 138
Shen liang Avatar answered Sep 24 '22 18:09

Shen liang