2010-11-27 11 views
7

मैं सी # के लिए नया हूं, मैं किसी ऑब्जेक्ट के गुणों पर पुनरावृत्ति करने के लिए एक फ़ंक्शन लिखना चाहता हूं और सभी शून्य स्ट्रिंग को "" सेट करना चाहता हूं। मैंने सुना है कि "प्रतिबिंब" नामक किसी चीज़ का उपयोग करना संभव है लेकिन मुझे नहीं पता कि कैसे।सी # में किसी ऑब्जेक्ट के सभी गुणों को फिर से कैसे करें?

धन्यवाद

+2

कि एक काफी अजीब बात की तरह लगता है क्या कर रही किया जाना है। मुझे यह जानकर उत्सुकता है कि आप इसके साथ क्या हासिल करने की कोशिश कर रहे हैं? – andynormancx

+0

एक तरफ नोट पर, हो सकता है कि आप अपने नल स्ट्रिंग को "स्ट्रिंग.एक्टी" के बजाय "" पर सेट करना चाहें। असली दुनिया का प्रभाव नगण्य है, लेकिन कुशल कोड के लिए पूर्व एक नई वस्तु नहीं बनाता है। – Cranialsurge

+0

इसके अलावा, मैं andynormancx से सहमत हूं .... आपका उद्देश्य क्या है? – Cranialsurge

उत्तर

19
public class Foo 
{ 
    public string Prop1 { get; set; } 
    public string Prop2 { get; set; } 
    public int Prop3 { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var foo = new Foo(); 

     // Use reflection to get all string properties 
     // that have getters and setters 
     var properties = from p in typeof(Foo).GetProperties() 
         where p.PropertyType == typeof(string) && 
           p.CanRead && 
           p.CanWrite 
         select p; 

     foreach (var property in properties) 
     { 
      var value = (string)property.GetValue(foo, null); 
      if (value == null) 
      { 
       property.SetValue(foo, string.Empty, null); 
      } 
     } 

     // at this stage foo should no longer have null string properties 
    } 
} 
+2

+1 – Aliostad

+3

हां, पढ़ने/लिखने से पहले पढ़ने/लिखने की जांच महत्वपूर्ण है। –

+0

आपके उत्तर के लिए धन्यवाद। – Ristovak

1
foreach(PropertyInfo pi in myobject.GetType().GetProperties(BindingFlags.Public)) 
{ 
    if (pi.GetValue(myobject)==null) 
    { 
     // do something 
    } 
} 
संबंधित मुद्दे