最近我发现自己写了很多类类似于:
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/