访问静态代码块中的“this”

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

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> AllMyTypeCodes = new Lazy<IEnumerable>(() => { 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 All { get { return AllMyTypeCodes.Value; } } } 

如果你注意到new Lazy<IEnumerable>(() =>我特意需要做typeof(MyTypeCodes)即使我在类MyTypeCodes里面。有没有办法我可以写这个而不需要特别需要我特意在里面调用typeof() ?如果这是一个常规方法,我会使用this.GetType()显然不起作用(出于某种原因)。

有没有什么方法可以写这个没有特别需要调用typeof()为我特别在里面的类?

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

此外,您应该使用ToList()来防止生成的IEnumerable每次枚举时都必须重新运行:

 private static readonly Lazy> AllMyTypeCodes = new Lazy>(() => { 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(); }); 

创建一个私有构造函数,为您提供(私有)引用。

 private MyTypeCodes() { } private static MyTypeCodes _instance = new MyTypeCodes(); public static DoSomethingWithType() { return _instance.GetType().foo(); } 

或者您可以让构造函数调用GetType(),并且只需在每次需要时使用它而不是调用_instance.GetType()。

如果你更喜欢语义,你可以这样做:

 private static readonly Type _thisType = typeof(MyTypeCodes); // use like var typeCodes = _thisType.GetFields(...