2014-09-04 59 views
0

我想用反射來確定我的對象是在哪裏創建的。例如:找到對象實例化的地方

public class MyClass 
{ 
    public int Id { get; set; } 
    public string Message { get; set; } 
} 

public static class Students 
{ 
    public static class FirstGrade 
    { 
     public static MyClass John = new MyClass { Id = 1, Message = "Some Text" }; 
    } 
} 

現在在我的代碼別的地方我想用MyClass的對象約翰和與該對象我想,以確定約翰創建,這樣我可以識別他是一年級的學生。我也想知道對象名稱「John」,因爲這可能會改變:

MyClass student = Students.FirstGrade.John; 
+13

__Definitely__重新考慮這一點。如果僅僅用等級來標記物體本身,而不是使用反射,那會更容易。例如:'public int Grade {get;組; }'。你很快就會發現你正在做的事情非常痛苦。 – 2014-09-04 23:43:36

+0

謝謝Simon!我也這麼想過。我無法做到這一點的原因是因爲我還會有一個通用的類別和相同的約翰變量,並帶有不同的消息。因此,當我的應用程序運行時,它會調用通用約翰,並在運行時檢測到存在特定的一級約翰,我希望通用值由特定值替換。對不起,如果這很難理解! – Mpressiv 2014-09-05 00:46:38

回答

1

我想下面是你所要求的。或者,如果您想知道對象是在哪裏創建的,而不僅僅是其引用的位置,則可以訪問MyClass構造函數中的System.Diagnostics.StackTrace對象。

正如其他人所說,似乎應該重新考慮設計。

public static class Students 
{ 

    public static class FirstGrade { 
     public static MyClass John = new MyClass { Id = 1, Message = "Some Text" }; 
    } 

    public static class SecondGrade { 
     public static MyClass John = new MyClass { Id = 2, Message = "Some Text" }; 
    } 

    public static Type FindStudent(MyClass s, out String varName) { 
     varName = null; 
     foreach (var ty in typeof(Students).GetNestedTypes()) { 
      var arr = ty.GetFields(BindingFlags.Static | BindingFlags.Public); 
      foreach (var fi in arr) { 
       if (fi.FieldType == typeof(MyClass)) { 
        Object o = fi.GetValue(null); 
        if (o == s) { 
         varName = fi.Name; 
         return ty; 
        } 
       } 
      } 
     } 
     return null; 
    } 

    public static void FindJohn() { 
     String varName = null; 
     Type ty = FindStudent(SecondGrade.John, out varName); 
     MessageBox.Show(ty == null ? "Not found." : ty.FullName + " " + varName); 
    } 
} 
+0

這就是我一直在尋找的!我使用FindStudent方法結合另一種方法遞歸地查找所有嵌套類型(因爲它可能超過一個深度)。謝謝! – Mpressiv 2014-09-05 20:25:26