繁体   English   中英

如何在 c# 中将 Object 转换为另一种类型?

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

我无法复制确切的代码,所以这将是一个示例:假设我们有一个带有名称和类型的类 Car。

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

我从输入中获取一些值,然后将其放入对象中(这不仅可以是汽车,也可以是其他类型)。 如果对象是汽车,我想访问名称和类型。

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;
 }

我刚刚意识到缺少的功能是:价值。 如此正确:


if (obj.Value is Car car)
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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