简体   繁体   English

如何从 static class 中获取常量到列表中<selectlistitem></selectlistitem>

[英]How to get constants from a static class into a List<SelectListItem>

I have a static class with constants that I want to store in a list to be used in a DropDown我有一个带有常量的 static class ,我想将其存储在要在下拉列表中使用的列表中

public static class DateFormatConstant
{
    [Display(Name = "DD/MM/YYYY")]
    public const string DayMonthYear = "dd/MM/yyyy";
    [Display(Name = "MM/DD/YYYY")]
    public const string MonthDayYear = "MM/dd/yyyy";
    [Display(Name = "YYYY/MM/DD")]
    public const string YearMonthDay = "yyyy/MM/dd";
    [Display(Name = "MM/DD/YY")]
    public const string MonthDayTwoDigitYear = "MM/dd/yy";
}

Is there a way to get them into a List<SelectListItem> ?有没有办法让它们进入List<SelectListItem>

The answer from @maembe utilizing Reflection is a good way to go. @maembe 利用反射的答案是 go的好方法。 But since you already are decorating your constants with the Display attribute I'll expand this solution to use the attribute.但是由于您已经使用Display属性来装饰常量,因此我将扩展此解决方案以使用该属性。 Note that I use LINQ's Query Syntax here as opposed to the Method Syntax in the other answer.请注意,我在这里使用 LINQ 的查询语法,而不是其他答案中的方法语法。

Here's my code:这是我的代码:

var selectLisItems =
    from f in typeof(DateFormatConstant).GetFields(BindingFlags.Public | BindingFlags.Static)
    where f.IsLiteral && f.FieldType == typeof(string)
    from a in f.CustomAttributes
    where a.AttributeType == typeof(DisplayAttribute)
    let na = a.NamedArguments.First(x => x.MemberName == nameof(DisplayAttribute.Name))
    select new SelectListItem
    {
        Text = (string)na.TypedValue.Value,
        Value = (string)f.GetRawConstantValue()
    };

var list = selectLisItems.ToList();

What does it actually do?它实际上是做什么的? Let's look at the parts of the query.让我们看一下查询的部分。

    from f in typeof(DateFormatConstant).GetFields(BindingFlags.Public | BindingFlags.Static)
    where f.IsLiteral && f.FieldType == typeof(string)

Here I'm selecting all constants from the DateFormatConstant class that are of type string .在这里,我从DateFormatConstant class 中选择string类型的所有常量。

    from a in f.CustomAttributes
    where a.AttributeType == typeof(DisplayAttribute)

Now I'm limiting to constants that actually have the Display attribute.现在我限制在实际具有Display属性的常量上。 Note that the "real" type here is DisplayAttribute注意这里的“真实”类型是DisplayAttribute

    let na = a.NamedArguments.First(x => x.MemberName == nameof(DisplayAttribute.Name))

Next is going through the arguments of the attribute and search for Name .接下来是通过属性的 arguments 并搜索Name I can safely use First here because I already limited to the DisplayAttribute type and know therefore that it has a Name property.我可以在这里安全地使用First ,因为我已经限制了DisplayAttribute类型,因此知道它有一个Name属性。

    select new SelectListItem
    {
        Text = (string)na.TypedValue.Value,
        Value = (string)f.GetRawConstantValue()
    };

var list = selectLisItems.ToList();

At last I'm constructing SelectListItem from the attribute and the fields and create the desired List<SelectListItem> from the query.最后,我从属性和字段构造SelectListItem并从查询中创建所需的List<SelectListItem>

Note: All this assumes that you want all string constants from your class to be contained in the list.注意:所有这些都假设您希望 class 中的所有字符串常量都包含在列表中。 If your class contains more constants that should go in different lists you can use the GroupName property of the Display attribute to group constants together.如果您的 class 包含更多常量,应该 go 在不同的列表中,您可以使用Display属性的GroupName属性将常量组合在一起。 I'll leave it as an excercise to expand the code accordingly.我将把它作为练习来相应地扩展代码。

If you want to do it automatically, you would need to use reflection:如果要自动执行此操作,则需要使用反射:

IEnumerable<SelectListItem> fields = typeof(DateFormatConstant).GetFields(BindingFlags.Public | BindingFlags.Static)
    .Where(f => f.IsLiteral && !f.IsInitOnly) // all the constant fields
    .Select(f => new SelectListItem() {    //convert to SelectListItem
            Text = ((string)f.GetRawConstantValue()).ToUpper(),
            Value = (string)f.GetRawConstantValue()
        });

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

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