通常,如果对象是类实例,我会使用反射为其成员设置值。考虑以下:
class Foo
{
public Control _tCtrl { get; set; }
public Object _tObj { get; set; }
public void Set()
{
// How do I give tObj the converted value of _tCtrl.ToString() ?
// var val = Convert.ChangeType( _tCtrl.ToString(), tObj.GetType() );
// _tObj.SetValue( val );
}
}
调用它就像:
Class Bar
{
public Int32 _i { get; set; }
}
Bar bar = new Bar();
Foo foo = new Foo();
foo._tCtrl = new TextBox() { Text = "100" };
foo._tObj = bar._i;
foo.Set();
或者:
Foo foo = new Foo();
Int32 i;
foo._tCtrl = new TextBox() { Text = "100" };
foo._tObj = i;
foo.Set();
任何东西都可以传递给 Set()。假设我可以从 a 转换String
为tObj.GetType()
.