2011-07-11 22 views
-1

我有一個以通用方式從構造函數中獲取值的問題。我如何在構造函數中獲取使用的參數的值(C#)

namespace myTestNamespace 
{ 
    Public Class myTestClass() 
    { 
     Public myTestClass(int myInt,bool myBool, double myDouble) 
     { 
     //do/set something 
     } 

     Public myTestClass(int myInt,bool myBool) 
     { 
      //do/set something 
     } 
    } 
} 

Using (what you need); 
Using myTestNamespace; 

namespace MyIWannaLookForTheParametersName 
{ 
    Public Class MyLookUpClass() 
    { 
     Public void DoSomething() 
     { 
     List<object> myList = new List<object>(); 

     myTestClass _ myTestClass = new myTestClass(1,true,2.5); 
     object mySaveObject = myTestClass; 

     mylist.Add(mySaveObject); 

     //how do I get the info from the right constructor 
     //(I used the one with 3 parameters_ 
     //what was the value of myInt, myBool and myDouble 
     //how can I make it generic enough, so it will work with other classes with 
     // different constructors ass well? 
     } 
     } 
    } 
+2

這不是完全清楚你想要做什麼,說實話。不應該把所有的信息都放在對象本身中嗎?你爲什麼關心它是如何構建的? –

+0

你能舉一個你想要做什麼的例子嗎? (你有什麼和你想要什麼...) –

+0

這應該做什麼? –

回答

0

我得到了什麼,我需要用這種方法:

private static ParameterSettings[] GetListOfParametersFromIndicator(object indicatorClass, int loopId, myEnums.ParaOrResult paraOrResult) 
    { 
     return (from prop in indicatorClass.GetType().GetProperties() 
       let loopID = loopId 
       let Indicator = indicatorClass.GetType().Name 
       let value = (object)prop.GetValue(indicatorClass, null) 
       where prop.Name.Contains("_Constr_") 
       select new ParameterSettings { ParaOrResult=paraOrResult, LoopID= loopId, Indicator= Indicator, ParaName= prop.Name, Value= value }).ToArray(); 
    } 

其中ParameterSettings是:

public struct ParameterSettings 
    { 
     public myEnums.ParaOrResult ParaOrResult { get; set; } 
     public int     LoopID   { get; set; } 
     public string    Indicator  { get; set; } 
     public string    ParaName  { get; set; } 
     public object    Value   { get; set; } 
    } 

這個信息是確定對我來說。感謝您的回覆。

問候,

Matthijs

+0

請注意這存在潛在的性能問題 - 傳入的參數可能是巨大的對象,並且通過在內存中保留對它們的引用,可以防止它們被GC_d所阻止。根據您的需要,執行'.ToString'可能會爲您提供99%的信息以獲得更易於管理的內存預算 – Basic

0

您無法從構造函數中獲取值。您需要先將它們放置在班級中的某個屬性或字段中。你提供的例子是泛型的一個不好的用法。你最好把構造函數的值放入屬性中,並創建一個與這些屬性的接口。

1

關於意圖的問題放在一邊,有沒有通用的方式來做到這一點。有關已調用哪些方法以及提供的值的信息不會自動保存。當然,你完全能夠自己跟蹤這些事情,但是你必須寫出每個班級明確地做到這一點。

以通用的方式進行此操作會造成麻煩。如果我這樣做呢?

public class Foo 
{ 
    public string Name { get; set; } 
} 

public class Bar 
{ 
    public Bar(Foo foo) 
    { 
     // ... 
    } 
} 

然後假設我把它叫做這樣:

Foo f = new Foo(); 

f.Name = "Jim"; 

Bar b = new Bar(f); 

f.Name = "Bob"; 

現在,如果這樣一個通用的系統存在,會是什麼fooBar構造的價值?它要麼報告"Bob"(這是Name的值是在提供的Foo的實例中的值),要麼報告"Jim",這意味着運行時或庫本質上必須足夠聰明以便對該對象進行深度複製國家沒有改變。底線是這樣的:如果你需要訪問傳遞給構造函數(或任何其他函數)的參數,你必須明確地將它們存儲在某個地方。

相關問題