开发者

Getting a Type variable knowing the name of type C#

I'm developing a TypeTranslator class which has a method Type TranslateType(Type type). This method gets a type of an interface and if there's a class of interface name without leading I it creates it, otherwise an exception is raised.

Here's some code to clearify what's written before:

class Program
{
    interface IAnimal { }
    class Animal : IAnimal { }

void Function()
{
    TypeTranslator typeTranslator = new TypeTranslator();
    Assert(typeTranslator.TranslateType(typeof(IAnimal) == typeof(Animal)));
}

}

Is it possible to get what I want?

Thank you for your hel开发者_开发百科p!


Look at Type.GetType. The documentation can be found here.


Do you want to get a type name from a string variable? If yes, then you can use Type.GetType method. Of course, the method expects the type name to be qualified by its namespace. Alternatively, if you don't want to restrict the type to a specific namespace, you can grab all types in an assembly with Assembly.GetTypes method and look for a type with a specific name.


Have you heard about dependeny injection? Maybe this is exactly what you need ...

See what is dependency injection and maybe on wikipedia for more infos, too.


You may want to have a look at Object.GetType(), Assembly.GetTypes() (using Assembly.GetExecutingAssembly(), for example) , Type.IsClass, Type.IsInterface, Type.Name (which is like FullName but without the full qualifier) and the Activator class to create an instance. It's basically getting all types, looping over them, checking whether they are class types and whether their name is the one of the interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜