简体   繁体   English

Linq-将静态类常量获取为列表

[英]Linq - Get the Static class constants as List

Here is my static class holding the constants 这是我的常量的静态类

public static class Files
{
    public const string FileA = "Block1";
    public const string FileB = "Block2";
    public const string FileC = "Block3";
    public const string FileD = "Block6.Block7";
 }

By any chance, is it possible to get constants as list using LINQ other than converting it to data tables and retrieve. 除了将其转换为数据表并进行检索外,还可以使用LINQ将常量作为列表获取。 Thanks 谢谢

Hope that you are looking for something like this : 希望您正在寻找这样的东西:

List<string> staticconstList = new List<string>(); 
Type type = typeof(Files);
foreach (var field in type.GetFields())

{
    var val = field.GetValue(null);               
    staticconstList.Add(val.ToString());
}

Or something like This: 或类似这样的东西:

List<string> staticconstList = type.GetFields().Select(x => x.GetValue(null).ToString()).ToList();

With reflection you can go like this, the result a enumerable with a Field, Value structure. 通过反射,您可以像这样进行操作,结果可以用字段,值结构枚举。

using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication2
{
    public static class Files
    {
        public const string FileA = "Block1";
        public const string FileB = "Block2";
        public const string FileC = "Block3";
        public const string FileD = "Block6.Block7";
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            var t = typeof(Files);
            var fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);

            var list = fields.Select(x => new {Field = x.Name, Value = x.GetValue(null).ToString()});


            Console.Read();
        }
    }
}

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

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