使用属性名称设置属性值

41

可能是重复问题:
我可以使用反射来设置属性值吗?

当我只有类的静态属性名称的字符串时,如何使用反射来设置类的静态属性?例如:

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);
3个回答

50

你可以尝试像这样做

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); 
  } 

27

你可以这样获取 PropertyInfo 并设置其值

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

我创建了几个方法来保存和加载应用程序设置,这些设置在应用程序内部是一个静态类,使用反射。谢谢。 请参见http://www.sportronics.com.au/csharp/Savings-and-Loading-Application-Settings-through-Refection-csharp.html - David Jones
1
@DavidJones。我遇到了404错误。 - Beatles1692
抱歉,试试这个链接:http://www.sportronics.com.au/appdev/Savings-and-Loading-Application-Settings-through-Refection-appdev.html(已更新) - David Jones

2

就像这样:

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 ;
  }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接