如何创建对象C#

时间:2017-05-28 15:58:15

标签: c# json object

如果您有以下代码,如何在C#中创建对象:

namespace WindowsFormsApp
{
    class Car
    {

        public class Id
        {
            public string brand { get; set; }
            public string model { get; set; }
            public string year { get; set; }
            public string r_no { get; set; }
            public string owner { get; set; }
        }

        public class Tires
        {
            public string front_value_mm { get; set; }
            public string back_value_mm { get; set; }
            public bool front_back { get; set; }
        }
}
}

我试着写这样的东西: (这是我第一次使用c#)

I  Car car = new Car();
            Car.Id = car("Toyota", "Corolla", "1995", "AE2445", "James Cordel");

我知道它无权构建。所以我问我是不是正确地创建了这个代码? 我需要创建一个新的汽车对象,它将包含有关汽车的所有信息,稍后,我想将有关已创建汽车的信息发送到json文件中。

3 个答案:

答案 0 :(得分:0)

简短回答:

# You want to create object of Car.Id, so declare variable of that type
Car.Id carId;

# Then you create "new" Car.Id:
carId = new Car.Id {
    brand = "Toyota",
    model = "Corolla",
    year = "1995",
    r_no = "AE2445",
    owner = "James Cordel",
}

答案 1 :(得分:0)

创建子类的实例

希望这会有所帮助。请记住,代码中的每个位置都可以访问公共类。

Car.Id id = new Car.Id();
  id = new Car.Id
  {
    brand = "Toyota",
    model = "Corolla",
    owner = "James Cordel",
    year = "1995",
    r_no = "AE2445"
  };

答案 2 :(得分:0)

您应该将类​​分开并将嵌套类用作属性类型。

namespace WindowsFormsApp
{
    class Car
    {
        public Id Id { get; set; }
        public Tires Tires { get; set; }
    }

    public class Id
    {
        public string brand { get; set; }
        public string model { get; set; }
        public int year { get; set; }
        public string r_no { get; set; }
        public string owner { get; set; }
    }

    public class Tires
    {
        public string front_value_mm { get; set; }
        public string back_value_mm { get; set; }
        public bool front_back { get; set; }
    }
}

现在你可以使用嵌套值来修改汽车类。

var car = new Car
{
    Id = new Id 
    {
        brand = "Honda",
        model = "Civic",
        year = 2017,
        r_no = "r_no",
        owner = "owner"
    },

    Tires = new Tires
    {
        front_value_mm = "front_value_mm",
        back_value_mm = "back_value_mm",
        front_back = true
    }
}

然后,您应该可以像这样访问嵌套属性。

var brand = Car.Id.brand // Honda

如果要使用参数指定值,则需要构造函数方法。