2015-06-23 36 views
0

在我們的報告環境,我們有一個方法來獲取數據源,它看起來像這樣:反思獲取內部變量的結果值

protected override IEnumerable<ReportDataSource> GetDataSources(IEnumerable<ReportParameter> parameters) 
{ 
    return new List<ReportDataSource> 
    { 
     new ReportDataSource("DataSource1", GetDataSource1(parameters)), 
     new ReportDataSource("DataSource2", GetDataSource2(parameters)) 
    }; 
} 

從調用的方法爲不用ICollections。我的問題是,爲了文檔的目的,我需要知道這些集合的內部類型,最好不用調用該方法。我只需要他們正在做的叫聲,我通過打破了下來局部變量:

const string dataSourcesMethodName = "GetDataSources"; 

MethodInfo methodInfo = type.GetMethod(
    dataSourcesMethodName, 
    BindingFlags.Instance | BindingFlags.NonPublic, 
    Type.DefaultBinder, 
    new[] { typeof(IEnumerable<ReportParameter>) }, 
    null); 

    var methodBody = methodInfo.GetMethodBody(); 
    var variable = methodBody.LocalVariables.First(f => f.LocalType == typeof(IEnumerable<ReportDataSource>)); 

它甚至有可能獲得我需要在不調用此方法的信息?

+2

如果你看看源代碼,GetDataSource1(parameters)會返回什麼?因爲如果它返回'ICollection ',很容易提取'something' ...但是如果它返回一個'ICollection',幾乎不可能發現它正在做什麼。 – xanatos

+0

可悲只是一個ICollection,但我想變量類型有這些信息? –

+1

只有該集合中的成員才能獲得此信息,因爲您可以在其中存儲任何東西。 – HimBromBeere

回答

1

簡單的說,你不能沒有執行方法...一些例子(見http://goo.gl/8QN19K):

C#:

public ICollection M1() { 
    ICollection col = new List<string>(); 
    return col; 
} 

public ICollection M2() { 
    ArrayList col = new ArrayList(); 
    col.Add("Hello"); 
    return col; 
} 

IL代碼當地人:

.locals init (
    [0] class [mscorlib]System.Collections.ICollection, 
    [1] class [mscorlib]System.Collections.ICollection 
) 

.locals init (
    [0] class [mscorlib]System.Collections.ArrayList, 
    [1] class [mscorlib]System.Collections.ICollection 
) 

在Release模式編譯它更差,當地人會完全消失......見例如http://goo.gl/yvWZHR

一般來說這些方法可以使用例如一個ArrayList,所以非類型化的集合(如M2方法)。祝你好運,找到它的元素的類型,而不執行方法和解析一些元素。

+0

嗯,值得一試我想,謝謝澄清 –