简体   繁体   English

在不同的类C#中初始化数组对象

[英]Initialize array object inside a different class C#

I would like to understand how to initialize array object from an outside class. 我想了解如何从外部类初始化数组对象。 Please refer to the code below: 请参考以下代码:

Class C
{
    private string name { get; set; }
    private string value { get; set; }
}

Class B
{
    private C[] field;
    public C[] Field { get; set; };
}

Class Program 
{
    public static void Main(string[] args)
    {
        B b = new B();
        /* my question was how to initialize this array object inside B class */
        b.Field = new C[1]; 
        b.Field[0] = new C(); 
        /* Now I can access b.Field[0].name */ 
    }
}

Note that I cannot change Classes B and C as they are already provided to me. 请注意,我不能更改类B和C,因为它们已经提供给我。 Thanks for your help. 谢谢你的帮助。

First of all, you can not modify name and value properties from outside of C because they are private. 首先,您不能从C外部修改名称和值属性,因为它们是私有的。
After making your name and value properties public, you can instantiate your array as follows. 在公开您的名称和值属性后,您可以按如下方式实例化您的数组。

B b = new B();
b.Field = new C[] {new C {name = "lorem", value = "ipsum"}, new C {name = "dolor", value = "sit"}};

If you use Reflection, create your C objects through a factory as follows. 如果使用Reflection,请通过工厂创建C对象,如下所示。

public class CFactory
{
    public C Create(string name, string value)
    {
        C result = new C();
        var props = result.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public
                                                | BindingFlags.Instance | BindingFlags.Static);

        var nameProp = props.FirstOrDefault(p => p.Name == "name");
        var valProp = props.FirstOrDefault(p => p.Name == "value");

        if (nameProp != null) nameProp.SetValue(result, name);
        if (valProp != null) valProp.SetValue(result, value);

        return result;
    }
}

and use it; 并使用它;

B b = new B();
var fac = new CFactory();
b.Field = new C[] {fac.Create("lorem", "ipsum"), fac.Create("dolor", "sit")};

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

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