2011-04-01 12 views
95

पर आधारित संपत्ति मूल्य कैसे प्राप्त करें, किसी नाम की वस्तु के आधार पर किसी ऑब्जेक्ट की संपत्ति का मूल्य प्राप्त करने का कोई तरीका है?नाम

उदाहरण के लिए अगर मेरे पास है:

public class Car : Vehicle 
{ 
    public string Make { get; set; } 
} 

और

var car = new Car { Make="Ford" }; 

मैं एक तरीका है जहाँ मैं संपत्ति के नाम पर पारित कर सकते हैं लिखने के लिए चाहते हैं और यह संपत्ति के मूल्य वापसी होगी। अर्थात्:

public static object GetPropertyValue(this object car, string propertyName) 
{ 
    return car.GetType().GetProperties() 
     .Single(pi => pi.Name == propertyName) 
     .GetValue(car, null); 
} 

और फिर:

public string GetPropertyValue(string propertyName) 
{ 
    return the value of the property; 
} 

उत्तर

211
return car.GetType().GetProperty(propertyName).GetValue(car, null); 
+8

नामक चर रखने की आवश्यकता नहीं है, ध्यान रखें कि चूंकि यह प्रतिबिंब का उपयोग करता है, यह बहुत धीमा है। शायद कोई मुद्दा नहीं, लेकिन इसके बारे में जागरूक होना अच्छा है। –

+0

"स्ट्रिंग से बाइंडिंगफ्लैग में कनवर्ट नहीं किया जा सकता" – Hill

+0

क्या @ मैटग्रेयर "तेज" तरीका है? – FizxMike

32

परावर्तन

public object GetPropertyValue(object car, string propertyName) 
{ 
    return car.GetType().GetProperties() 
     .Single(pi => pi.Name == propertyName) 
     .GetValue(car, null); 
} 

उपयोग करने के लिए क्या तुम सच में फैंसी होना चाहते हैं होगा, आप इसे एक विस्तार विधि बना सकता है

string makeValue = (string)car.GetPropertyValue("Make"); 
+0

आप SetValue –

+0

हाँ के बजाय GetValue चाहते हैं, मैंने इसे भी पकड़ा, धन्यवाद! –

+0

क्या मैं इसे SetValue के लिए भी कर सकता हूं? कैसे? –

24

आप चाहते प्रतिबिंब

Type t = typeof(Car); 
PropertyInfo prop = t.GetProperty("Make"); 
if(null != prop) 
return prop.GetValue(this, null); 
+2

+1 यह सबसे अच्छा जवाब है क्योंकि आप सभी मध्यवर्ती वस्तुओं को दिखा रहे हैं –

2

सरल नमूना

class Customer 
{ 
    public string CustomerName { get; set; } 
    public string Address { get; set; } 
    // approach here 
    public string GetPropertyValue(string propertyName) 
    { 
     try 
     { 
      return this.GetType().GetProperty(propertyName).GetValue(this, null) as string; 
     } 
     catch { return null; } 
    } 
} 
//use sample 
static void Main(string[] args) 
    { 
     var customer = new Customer { CustomerName = "Harvey Triana", Address = "Something..." }; 
     Console.WriteLine(customer.GetPropertyValue("CustomerName")); 
    } 
0

इसके अलावा अन्य लोगों का जवाब है, इसके आसान किसी भी वस्तु उपयोग के द्वारा की संपत्ति के मूल्य प्राप्त करने के लिए (ग्राहक में लिखने प्रतिबिंब कठिन कोड के बिना) एक्सटेंशन विधि की तरह:

public static class Helper 
    { 
     public static object GetPropertyValue(this object T, string PropName) 
     { 
      return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null); 
     } 

    } 

प्रयोग है:

Car foo = new Car(); 
var balbal = foo.GetPropertyValue("Make"); 
संबंधित मुद्दे