2011-04-21 51 views
0

訪問常量這是一個後續How to invoke static method in C#4.0 with dynamic type?與動態關鍵字

有沒有辦法用double.MaxValue,int.MaxValue等工作時,通過使用動態關鍵字和/或仿製藥,以消除重複?

人爲的例子:

T? Transform<T>(Func<T?> continuation) 
    where T : struct 
    { 
    return typeof(T).StaticMembers().MaxValue; 
    } 
+1

什麼樣的重複? – Andrey 2011-04-21 20:24:51

+1

@ .net常量中的GregC不是編譯時。 – Andrey 2011-04-21 20:25:22

+0

@Andrey:我用一個例子更新了我的Q – GregC 2011-04-21 20:27:30

回答

1

修改類StaticMembersDynamicWrapper這樣:

public override bool TryGetMember(GetMemberBinder binder, out object result) { 
    PropertyInfo prop = _type.GetProperty(binder.Name, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public); 
    if (prop == null) { 
     FieldInfo field = _type.GetField(binder.Name, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public); 
     if (field == null) 
     { 
      result = null; 
      return false; 
     } 
     else 
     { 
      result = field.GetValue(null, null); 
      return true; 
     } 
    } 

    result = prop.GetValue(null, null); 
    return true; 
} 

你的代碼的問題是,它僅檢索屬性,但常量實際上領域。

0

隨着一點點的風格和才華,同樣的代碼:

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; 
    } 
}