简体   繁体   中英

How do you convert in c# an Object to another type?

I can't copy exact code so this will be an example: Let's say we have a class Car with Name and Type.

 public class Car
  {
     public string Name { get; set; } = string.Empty;
    public string Type{ get; set; } = string.Empty;
  }

I get some values from an input, which I put in an object (this can be other type as well not only car). If the object is car i would like to acces the Name and Type.

Object obj =//get's input data
bool result;
bool result = obj is Car;
if(result)
 {
  //how do I do the convertion here?
  //I tried the following, but it's not working:
  Car car= obj.Values;
 }

I just realised that the missing function was : Value. So correctly:


if (obj.Value is Car car)
{
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM