2012-02-22 26 views
16

संभव डुप्लिकेट:
Can I set a property value with Reflection?सेट संपत्ति के मूल्य संपत्ति का उपयोग कर नाम

मैं कैसे प्रतिबिंब का उपयोग कर जब मैं केवल संपत्ति के अपने स्ट्रिंग नाम है एक वर्ग के एक स्थिर गुण सेट करते हैं? उदाहरण के लिए मेरे पास है:

List<KeyValuePair<string, object>> _lObjects = GetObjectsList(); 

foreach(KeyValuePair<string, object> _pair in _lObjects) 
{ 
    //class have this static property name stored in _pair.Key 
    Class1.[_pair.Key] = (cast using typeof (_pair.Value))_pair.Value; 
} 

मुझे नहीं पता कि मुझे संपत्ति नाम स्ट्रिंग का उपयोग करके संपत्ति का मूल्य कैसे सेट करना चाहिए। सब कुछ गतिशील है। मैं सूची में 5 आइटम का उपयोग करके कक्षा के 5 स्थैतिक गुणों को स्थापित कर सकता हूं जिनमें प्रत्येक के अलग-अलग प्रकार होते हैं।

आपकी मदद के लिए धन्यवाद।

उत्तर:

Type _type = Type.GetType("Namespace.AnotherNamespace.ClassName"); 
PropertyInfo _propertyInfo = _type.GetProperty("Field1"); 
_propertyInfo.SetValue(_type, _newValue, null); 

उत्तर

16

आप इस

List<KeyValuePair<string, object>> _lObjects = GetObjectsList(); 
var class1 = new Class1(); 
var class1Type = typeof(class1); 
foreach(KeyValuePair<string, object> _pair in _lObjects) 
    { 
     //class have this static property name stored in _pair.Key  
     class1Type.GetProperty(_pair.Key).SetValue(class1, _pair.Value); 
    } 
9

आप इस तरह PropertyInfo हो और मूल्य निर्धारित कर सकते हैं

var propertyInfo=obj.GetType().GetProperty(propertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); 
propertyInfo.SetValue(obj, value,null); 
1

इस तरह की तरह कुछ की कोशिश कर सकते हैं:

class Widget 
{ 
    static Widget() 
    { 
    StaticWidgetProperty = int.MinValue ; 
    return ; 
    } 
    public Widget(int x) 
    { 
    this.InstanceWidgetProperty = x ; 
    return ; 
    } 
    public static int StaticWidgetProperty { get ; set ; } 
    public  int InstanceWidgetProperty { get ; set ; } 
} 

class Program 
{ 
    static void Main() 
    { 
    Widget myWidget = new Widget(-42) ; 

    setStaticProperty<int>(typeof(Widget) , "StaticWidgetProperty" , 72) ; 
    setInstanceProperty<int>(myWidget , "InstanceWidgetProperty" , 123) ; 

    return ; 
    } 

    static void setStaticProperty<PROPERTY_TYPE>(Type type , string propertyName , PROPERTY_TYPE value) 
    { 
    PropertyInfo propertyInfo = type.GetProperty(propertyName , BindingFlags.Public|BindingFlags.Static , null , typeof(PROPERTY_TYPE) , new Type[0] , null) ; 

    propertyInfo.SetValue(null , value , null) ; 

    return ; 
    } 

    static void setInstanceProperty<PROPERTY_TYPE>(object instance , string propertyName , PROPERTY_TYPE value) 
    { 
    Type type = instance.GetType() ; 
    PropertyInfo propertyInfo = type.GetProperty(propertyName , BindingFlags.Instance|BindingFlags.Public , null , typeof(PROPERTY_TYPE) , new Type[0] , null) ; 

    propertyInfo.SetValue(instance , value , null) ; 

    return ; 
    } 

} 
संबंधित मुद्दे