随着一点点的风格和才华,同样的代码:
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
PropertyInfo prop = _type.GetProperty(binder.Name,
BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public);
if (prop != null)
{
result = prop.GetValue(null, null);
return true;
}
FieldInfo field = _type.GetField(binder.Name,
BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public);
if (field != null)
{
result = field.GetValue(null);
return true;
}
result = null;
return false;
}
和高速缓存类,以避免不必要的创建对象:
public static class StaticMembersDynamicWrapperExtensions
{
static Dictionary<Type, DynamicObject> cache =
new Dictionary<Type, DynamicObject>
{
{typeof(double), new StaticMembersDynamicWrapper(typeof(double))},
{typeof(float), new StaticMembersDynamicWrapper(typeof(float))},
{typeof(uint), new StaticMembersDynamicWrapper(typeof(uint))},
{typeof(int), new StaticMembersDynamicWrapper(typeof(int))},
{typeof(sbyte), new StaticMembersDynamicWrapper(typeof(sbyte))}
};
/// <summary>
/// Allows access to static fields, properties, and methods, resolved at run-time.
/// </summary>
public static dynamic StaticMembers(this Type type)
{
DynamicObject retVal;
if (!cache.TryGetValue(type, out retVal))
return new StaticMembersDynamicWrapper(type);
return retVal;
}
}
什么样的重复? – Andrey 2011-04-21 20:24:51
@ .net常量中的GregC不是编译时。 – Andrey 2011-04-21 20:25:22
@Andrey:我用一个例子更新了我的Q – GregC 2011-04-21 20:27:30