C# Arrays as Class Properties

2019-08-27 15:55发布

问题:

I searched a lot but couldn't find any solution. I am probably using the wrong keywords. I have a class which is basically an extended version of ListView control.

I defined some custom attributes for my customized ListView, such as FileName, OrderType etc, and they work fine.

I also want to pass an array to my class which includes ColumnNames to populate the data within class.

In MyListView Class

public class ColumnNames : Attribute
{
    public string[] Values { get; set; }

    public ColumnNames(params string[] values)
    {
        this.Values = values;
    }
}

[ColumnNames("a1","a2","a3","a4","a5","a6","a7","a8","a9")]

public MyListView() {

     for (int i = 0; i < 7; i++)
            this.Columns.Add(this.ColumnNames[i]);

    }

In Form1 Class

MyListView lstv = new MyListView();

lstv.ColumnNames[0] = "hede1";
lstv.ColumnNames[1] = "hede2";
lstv.ColumnNames[2] = "hede3";

EDIT : I simply couldn't achieve what I wanted. Could you show me a working example of this?

I use this listview to display information taken from a database. (I use ListView instead of DataGrid) I want to pass the column names to this class which will be used both for SQL query "SELECT xxxxx, yyyyy, zzzz FROM table;" and column names this.columns.add("xxxxx"); this.columns.add("yyyyy"); this.columns.add("zzzzz");

回答1:

If you want to stick to the attribute, you can access its data like this:

var attributes = this.GetType().GetCustomAttributes(typeof(ColumnNames), false);
foreach (var attr in attributes)
{
    var a = attr as ColumnNames;
    foreach (var column in a.Values)
    {
        this.Columns.Add(column);
    }
}


回答2:

You're adding columns in the class constructor, before the control is being initialized. Try to override the OnLoad event instead and do it there:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    foreach (var columnName in this.ColumnNames)
        this.Columns.Add(columnName);
}


回答3:

I think you are misunderstanding the purpose of attribute. An attribute describes a member or class, but seem to be trying to use it like inheritance.

Maybe this is what your are looking for:

public class MyListView{
   public string[] ColumnNames {get; set;}
}


标签: c# arrays class