c# 从 class 获取列表 <string>
c# get List<string> from class
我有一个带有 const 字符串的 class,
有什么方法可以将这些 class 的所有 const 字符串添加到列表中?
public class Permissions
{
public const string AccessHomePage = "AccessHomePage";
public const string AccessAdminPage = "AccessAdminPage";
...
}
一次添加管理员用户的所有权限会更容易
获取 class...
中所有字符串的列表目录
List<string> allPermissions =
会很好...
可能
给定
public class Permissions
{
public const string AccessHomePage = "AccessHomePage";
public const string AccessAdminPage = "AccessAdminPage";
}
例子
private static IEnumerable<string> GetConstants<T>()
=> typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.Where(x => x.FieldType == typeof(string) && x.IsLiteral && !x.IsInitOnly)
.Select(x => x.GetValue(null) as string);
用法
foreach (var item in GetConstants<Permissions>())
Console.WriteLine(item);
输出
AccessHomePage
AccessAdminPage
加入胡椒和盐调味
说明
BindingFlags.Public
Specifies that public members are to be included in the search.
BindingFlags.Static
Specifies that static members are to be included in the search.
BindingFlags.FlattenHierarchy
Specifies that public and protected static members up the hierarchy
should be returned. Private static members in inherited classes are
not returned. Static members include fields, methods, events, and
properties. Nested types are not returned.
Gets a value indicating whether the field can only be set in the body
of the constructor.
Gets a value indicating whether the value is written at compile time
and cannot be changed.
我有一个带有 const 字符串的 class,
有什么方法可以将这些 class 的所有 const 字符串添加到列表中?
public class Permissions
{
public const string AccessHomePage = "AccessHomePage";
public const string AccessAdminPage = "AccessAdminPage";
...
}
一次添加管理员用户的所有权限会更容易
获取 class...
List<string> allPermissions =
会很好...
可能
给定
public class Permissions
{
public const string AccessHomePage = "AccessHomePage";
public const string AccessAdminPage = "AccessAdminPage";
}
例子
private static IEnumerable<string> GetConstants<T>()
=> typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.Where(x => x.FieldType == typeof(string) && x.IsLiteral && !x.IsInitOnly)
.Select(x => x.GetValue(null) as string);
用法
foreach (var item in GetConstants<Permissions>())
Console.WriteLine(item);
输出
AccessHomePage
AccessAdminPage
加入胡椒和盐调味
说明
BindingFlags.Public
Specifies that public members are to be included in the search.
BindingFlags.Static
Specifies that static members are to be included in the search.
BindingFlags.FlattenHierarchy
Specifies that public and protected static members up the hierarchy should be returned. Private static members in inherited classes are not returned. Static members include fields, methods, events, and properties. Nested types are not returned.
Gets a value indicating whether the field can only be set in the body of the constructor.
Gets a value indicating whether the value is written at compile time and cannot be changed.