问题描述
我搜索了很多,但找不到任何解决方案。我可能使用错误的关键字。我有一个类,它基本上是一个扩展版本的ListView控件。
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.
我为我的自定义ListView定义了一些自定义属性,如FileName,OrderType等, 。
I defined some custom attributes for my customized ListView, such as FileName, OrderType etc, and they work fine.
我也想传递一个数组给我的类,包括ColumnNames来填充类中的数据。
I also want to pass an array to my class which includes ColumnNames to populate the data within class.
MyListView
类
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]);
}
在 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?
我使用此列表视图来显示从数据库中获取的信息。 (我使用ListView而不是DataGrid)我想传递的列名称,这个类将被用于SQL查询SELECT xxxxx,yyyyy,zzzz FROM table;和列名this.columns.add(xxxxx); this.columns.add(yyyyy); this.columns.add(zzzzz);
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");
推荐答案
如果要坚持使用属性,像这样:
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);
}
}
这篇关于C#数组作为类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!