c# - 访问静态代码块内的 "this"

标签 c# static grammar

最近我发现自己写了很多类类似于:

public class MyTypeCodes
{
    public static MyTypeCode E = new MyTypeCode{ Desc= "EEE", Value = "E" };
    public static MyTypeCode I = new MyTypeCode { Desc= "III", Value = "I" };

    private static readonly Lazy<IEnumerable<MyTypeCode>> AllMyTypeCodes =
        new Lazy<IEnumerable<MyTypeCode>>(() =>
        {
            var typeCodes = typeof(MyTypeCodes)
                 .GetFields(BindingFlags.Static | BindingFlags.Public)
                 .Where(x => x.FieldType == typeof (MyTypeCode))
                 .Select(x => (MyTypeCode) x.GetValue(null))
                 .ToList();

                 return typeCodes;
        });

    public static IEnumerable<MyTypeCode> All
    {
        get { return AllMyTypeCodes.Value; }
    }
}

如果您注意到 new Lazy<IEnumerable<MyTypeCode>>(() => 的内部我特别需要做的 typeof(MyTypeCodes)即使我在 MyTypeCodes 类中。有什么方法可以写这个而不需要特别调用 typeof()我具体在哪个类(class)?如果这是常规方法,我会 this.GetType()这显然不适用于静态(出于某种原因)。

最佳答案

Is there any way I can write this without specifically need to call typeof() for the class i'm specifically inside of?

不,这可能是最好的选择。如果您知道您永远不会添加任何其他类型的任何其他字段,则可以跳过 Where条款。

另外,你应该使用ToList()防止IEnumerable<T>每次枚举时都必须重新运行而生成:

private static readonly Lazy<IEnumerable<MyTypeCode>> AllMyTypeCodes =
    new Lazy<IEnumerable<MyTypeCode>>(() =>
    {
        return typeof(MyTypeCodes)
             .GetFields(BindingFlags.Static | BindingFlags.Public)
             // If you're not using any other fields, just skip this
             // .Where(x => x.FieldType == typeof (MyTypeCode ))
             .Select(x => (MyTypeCode) x.GetValue(null))
             .ToList();                 
    });

关于c# - 访问静态代码块内的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19324419/

相关文章:

c# - Azure 搜索合并索引操作返回异常

c# - 如何将 SaveAs Dialog 结果传递给 RelayCommand?

java - 在静态 block 中将已检查异常转换为未检查异常是标准/推荐做法吗?

c# - 线程竞速,为什么线程这么工作?

json - JSON 是否允许数字的正号?

使用 ANTLRv4 的 Java DSL 实现

parsing - 在词法输入序列时指定文字的字符名称是什么?

c# - 如何在 Compact Framework c# 中遍历 BindingSource 项

c# - 从图表控件中检索 DateTime x 轴值

ios - (const) 变量的范围未定义为 extern 或 static