简体   繁体   English

在不知道类型的情况下将值设置为Object

[英]Set value to Object without knowing type

Usually, if the object was a class instance, I'd use reflection to set values to its members. 通常,如果对象是类实例,则可以使用反射为其成员设置值。 Consider the following: 考虑以下:

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

Calling it would be like: 调用它就像:

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

Or: 要么:

Foo foo = new Foo();
Int32 i;

foo._tCtrl = new TextBox() { Text = "100" };
foo._tObj = i;

foo.Set();    

Anything could be passed into Set(). 任何东西都可以传递给Set()。 Assume that I can convert from a String to whatever type is tObj.GetType() . 假设我可以将String转换为tObj.GetType()任何类型。

I think what this boils down to is converting a string to any other type. 我认为这归结为将字符串转换为任何其他类型。 That has problems. 那有问题。 How would you convert a string to, say, a Form , a List<> , or a Random ? 您如何将字符串转换为FormList<>Random It would require you to write a converter for every type in the .NET Framework (or possibly every existing type in the universe). 这将要求您为.NET Framework中的每种类型(或Universe中的每种现有类型)编写一个转换器。

You shouldn't be trying to do this. 您不应该尝试这样做。 I don't know what you are trying to achieve, but there is almost surely a better way. 我不知道您要达到什么目标,但是几乎可以肯定有更好的方法。

There is no way to allow that kind of syntax, but you can do the following: 没有办法允许这种语法,但是您可以执行以下操作:

foo.Set(bar, "_i");

Where Set uses the following: 其中Set使用以下内容:

type.GetProperty(propertyName, Type.EmptyTypes).SetValue(tObj, value, Type.EmptyTypes);

Where propertyName , tObj , and value are defined elsewhere. 其中propertyNametObjvalue在其他位置定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM