C# Is it possible to get actual type out of a string representing that type? [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 04:18:39

问题


I have string "Car", and I would like to get the type Car from it. My class Car is:

namespace MySolution.MyProjectA
{
    public class Car
    {
      ...
    }
}

I trying getting type like this but it returns null:

Type myType = Type.GetType("MySolution.MyProjectA.Car"); // returns null

Given a string variable representing my type (i.e. "Car"), how do I get its Type Car?

UPDATE AND SOLUTION

Thanks to suggestion from @AsafPala here (Type.GetType("namespace.a.b.ClassName") returns null), I got it to work. Turns out if you are calling GetType from another project in your solution (which is another assembly), you have to provide also assembly name.

Since MySolution has 2 project MyProjectA and MyProjectB, these are 2 separate projects (or assemblies) in same solution so you need to provide fully specified assembly name of your type (that is MySolution.MyProjectA.Car) and assembly name (that is MySolution.MyProjectA) as comma separated as below:

Type myType = Type.GetType("MySolution.MyProjectA.Car,MySolution.MyProjectA");

UPDATE AND SOLUTION

Since I am calling this code in another project (which is same as assembly), I need to provide fully specified type name and assembly name as comma separated like so:

namespace MySolution.MyProjectB
{
    public class MyClass
    {
        ...
        ...
        public void MyMethod()
        {
             // this wont work, I get null back
             //Type myType = Type.GetType("MySolution.MyProjectA.Car");
             Type myType = Type.GetType("MySolution.MyProjectA.Car,MySolution.MyProjectA"); //this works
             ...
        }
    }
}

回答1:


Yes. You need to serialize the object to a string first. You can use json or xml as the serializer type.

Then on the other side you use the same serializer object to deserialize the string into an instance of your class.

https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

Account account = JsonConvert.DeserializeObject<Account>(json); 

http://www.janholinka.net/Blog/Article/11

XmlSerializer serializer = new XmlSerializer(typeof(List), new XmlRootAttribute("Products"));

StringReader stringReader = new StringReader(xmlString);

List productList = (List)serializer.Deserialize(stringReader);

And then after you deserialize you can get the Type of the object



来源:https://stackoverflow.com/questions/54681389/c-sharp-is-it-possible-to-get-actual-type-out-of-a-string-representing-that-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!