Задайте значение свойства, используя имя свойства
Возможный дубликат:
Можно ли задать значение свойства с помощью 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);
Ответы
Ответ 1
Вы можете попробовать что-то вроде этого
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);
}
Ответ 2
вы можете получить PropertyInfo как это и установить значение
var propertyInfo=obj.GetType().GetProperty(propertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
propertyInfo.SetValue(obj, value,null);
Ответ 3
Вот так:
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 ;
}
}