如何在没有参数的构造函数中为引用其他类的变量设置值?

时间:2017-06-07 01:30:50

标签: c#

我已经声明了一个变量列表,包括引用另一个类的变量。

public class order {

    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

}

我已经创建了get和set方法。如何在没有参数的构造函数中为变量customer分配值?

public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = ?
}

3 个答案:

答案 0 :(得分:1)

如果您只想实例化一位新客户,请尝试以下方法:

public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = new Customer();
}

答案 1 :(得分:1)

如果没有任何参数,您只能使用新实例初始化客户。

customer = new Customer();

或者如果您要对客户属性进行硬编码,则可以使用

customer = new Customer{ *provide the initial values here* };

例如,如果客户将FirstName和LastName作为其属性,

customer = new Customer{ FirstName = "someName" , LastName = "someLastName" };

答案 2 :(得分:0)

除了将客户设置为nullnew Customer()之外,您可以使用以下两种方法之一:

静态变量:

void Main()
{
    order_helper.customer = new Customer();
    var order = new order();
}

public static class order_helper
{
    public static Customer customer;
}

public class order
{
    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

    public order()
    {
        primaryid = 0;
        desc = String.Empty;
        customerid = 0;
        customer = order_helper.customer;
    }
}

或反思:

    var field =
        typeof(order)
            .GetField("customer", BindingFlags.Instance | BindingFlags.NonPublic);

    var order = new order();
    field.SetValue(order, new Customer());