2012-12-07 25 views
8

Để lưu trữ trạng thái của các quá trình khi xảy ra lỗi, tôi muốn liệt kê tất cả dữ liệu (tùy chỉnh) được lưu trữ trong AppDomain (theo SetData). Thuộc tính LocalStore là riêng tư và lớp AppDomain không thể kế thừa. Có cách nào để liệt kê các dữ liệu đó không?Liệt kê tất cả dữ liệu tùy chỉnh được lưu trữ trong AppDomain

+0

tại sao không chỉ lưu trữ tất cả thông tin phím (trước đây thiết lập với SetData) trong một số bộ sưu tập và sau khi truy vấn GetData fro mỗi chủ chốt trong bộ sưu tập đó? – Tigran

+0

Tôi đang tìm kiếm một giải pháp, trong đó quy trình không cần sử dụng triển khai cụ thể. Vì tôi không nghĩ rằng nó có thể, phương pháp mở rộng cho AppDomain đó là lưu trữ các phím thông qua. Tks cho trả lời của bạn. Nếu bạn có một đầu mối khác, đừng ngần ngại. –

Trả lời

5
 AppDomain domain = AppDomain.CurrentDomain; 
     domain.SetData("testKey", "testValue"); 

     FieldInfo[] fieldInfoArr = domain.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); 
     foreach (FieldInfo fieldInfo in fieldInfoArr) 
     { 

      if (string.Compare(fieldInfo.Name, "_LocalStore", true) != 0) 
       continue; 
      Object value = fieldInfo.GetValue(domain); 
      if (!(value is Dictionary<string,object[]>)) 
       return; 
      Dictionary<string, object[]> localStore = (Dictionary<string, object[]>)value; 
      foreach (var item in localStore) 
      { 
       Object[] values = (Object[])item.Value; 
       foreach (var val in values) 
       { 
        if (val == null) 
         continue; 
        Console.WriteLine(item.Key + " " + val.ToString()); 
       } 
      } 


     } 
+0

Giải pháp tốt. Cảm ơn bạn đã trả lời. –

2

Dựa trên Frank59's câu trả lời nhưng một chút ngắn gọn hơn:

var appDomain = AppDomain.CurrentDomain; 
var flags = BindingFlags.NonPublic | BindingFlags.Instance; 
var fieldInfo = appDomain.GetType().GetField("_LocalStore", flags); 
if (fieldInfo == null) 
    return; 
var localStore = fieldInfo.GetValue(appDomain) as Dictionary<string, object[]>; 
if (localStore == null) 
    return; 
foreach (var key in localStore.Keys) 
{ 
    var nonNullValues = localStore[key].Where(v => v != null); 
    Console.WriteLine(key + ": " + string.Join(", ", nonNullValues)); 
} 
1

Cùng một giải pháp, nhưng như một phương pháp # mở rộng F. Có thể không cần kiểm tra null. https://gist.github.com/ctaggart/30555d3faf94b4d0ff98

type AppDomain with 
    member x.LocalStore 
     with get() = 
      let f = x.GetType().GetField("_LocalStore", BindingFlags.NonPublic ||| BindingFlags.Instance) 
      if f = null then Dictionary<string, obj[]>() 
      else f.GetValue x :?> Dictionary<string, obj[]> 

let printAppDomainObjectCache() = 
    for KeyValue(k,v) in AppDomain.CurrentDomain.LocalStore do 
     printfn "%s" k 
Các vấn đề liên quan