【发布时间】:2017-03-05 19:32:44
【问题描述】:
给定以下类:
public class PayrollReport
{
[UiGridColumn(Name = "fullName",Visible = false,Width = "90")]
public string FullName { get; set; }
[UiGridColumn(Name = "weekStart", CellFilter = "date")]
public DateTime WeekStart { get; set; }
}
还有这个自定义属性
[AttributeUsage(AttributeTargets.All)]
public class UiGridColumn : Attribute
{
public string CellFilter { get; set; }
public string DisplayName { get; set; }
public string Name { get; set; }
public bool Visible { get; set; }
public string Width { get; set; }
}
我想为每个字段创建一个List<UiGridColumn>,只包含提供的值(我不希望跳过的属性为空)。
是否可以创建一个List<UiGridColumn>,其中每个List 项目仅具有提供的值? (我担心这是不可能的,但我想我会问)如果是这样,怎么做?
如果不是,我的第二个偏好是这样的字符串数组:
[{"name":"fullName","visible":false,"width":"90"},{"name":"weekStart","cellFilter":"date"}]
我宁愿不遍历每个 property 和 attribute 和 argument 来手动构建所需的 JSON 字符串,但我无法找到一种简单的方法来做到这一点。
public List<Object> GetUiGridColumnDef(string className)
{
Assembly assembly = typeof(DynamicReportService).Assembly;
var type = assembly.GetType(className);
var properties = type.GetProperties();
var columnDefs = new List<object>();
foreach (var property in properties)
{
var column = new Dictionary<string, Object>();
var attributes = property.CustomAttributes;
foreach (var attribute in attributes)
{
if (attribute.AttributeType.Name != typeof(UiGridColumn).Name || attribute.NamedArguments == null)
continue;
foreach (var argument in attribute.NamedArguments)
{
column.Add(argument.MemberName, argument.TypedValue.Value);
}
}
columnDefs.Add(column);
}
return columnDefs;
}
有没有更好的方法来做到这一点?
【问题讨论】:
标签: c#-4.0 json.net custom-attributes