简体   繁体   English

如何使用内联分配在C#对象中分配部分值

[英]How to assign Partial Values in a C# object using Inline Assignment

I'm having a Collection of a Model 我正在收集模型

public class MobileModelInfo
{
    public string Name { get; set; }
    public string Catagory { get; set; }
    public string Year { get; set; }
}

Public Class MainClass
{
    public MainClass()
    {
        MobileModelInfo mobObject = new MobileModelInfo();
        mobObject.Name = "Apple iPhone 6";
        SetMobileDetails(mobObject);
    }

    private void SetMobileDetails(MobileModelInfo mobObject)
    {
        mobObject.Catagory = "Ultra Smart Phone";
        mobObject.Year = "2015";
    }
}

In the SetMobileDetails() Method set the partial values to the Object of MobileModelInfo. 在SetMobileDetails()方法中,将部分值设置为MobileModelInfo的Object。 Here I need to assign the Values via Inline. 在这里,我需要通过内联分配值。 How Can I achieve this 我该如何实现

For Example: new MobileModelInfo() { Catagory = "Ultra Smart Phone", Year = "2015" } 例如: new MobileModelInfo() { Catagory = "Ultra Smart Phone", Year = "2015" }

Kindly assist me... 请帮助我...

Note: One of the Property is set in Constructor and the remaining Properties is going to set in SetMobileDetails() Method. 注意:其中一个属性是在构造函数中设置的,其余属性将在SetMobileDetails()方法中设置。

You can use named parameter but you need to pass the value for properties of object 您可以使用命名参数,但需要传递对象属性的值

private void SetMobileDetails(string catagory="", string year="")
{
    //...
}

You probably need to have a constructor that all three property values 您可能需要具有所有三个属性值的构造函数

public MainClass(string name, string catagory="", string year="")
{
    mobObject.Name = name;
    SetMobileDetails(catagory: "Ultra Smart Phone", year : "2015");
}

Use below code to solve your problem thank you. 使用下面的代码解决您的问题,谢谢。

void SetMobileDetails(String Catagory String Year )
{

    new MobileModelInfo() { Catagory = "Ultra Smart Phone", Year = "2015" }

}

Also Make overload of this for when property are change like below 还可以在属性如下更改时对此进行重载

 void SetMobileDetails(String Catagory)
    {

        new MobileModelInfo() { Catagory = "Ultra Smart Phone"}

    }

This is all you need: 这就是您所需要的:

public class MobileModelInfo
{
  public string Name { get; private set; }
  public string Catagory { get; set; }
  public string Year { get; set; }

  public MobileModelInfo(string name)
  {
    Name = name;
  }
}

Usage: 用法:

var iphone = new MobileModelInfo("Apple iPhone") {Catagory = "Mobile", Year = "2016"};

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

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