从“对象”类创建的对象不允许检索属性值

时间:2015-10-12 09:45:17

标签: c# object reflection propertyinfo

我有一个从“对象”类创建的对象,它包含我创建的列表。该列表是从名为“MyClass”的类创建的对象的集合。并且,该类包含两个字符串属性。

public Class MyClass 
{
    private string _propOne;
    public string PropOne
    {
       get {return _propOne;}
       set {_propOne=Value;}
    }

    private string _propTwo;
    public string PropTwo
    {
       get {return _propTwo;}
       set {_propTwo=Value;}
    }
}

我有一个返回“object”类对象的方法

private object GetData() 
{
    // It converts the list created to an object created from the class "object"
}

然后我调用下面的方法。

object temp=GetData();

现在我想迭代“temp”并将其分配给从“MyClass”类的对象创建的另一个列表。

private List<MyClass> _anotherCollection;
public List<MyClass> AnotherCollection
{
   get {return _anotherCollection;}
   set {_anotherCollection=Value;}
}

........................

foreach (var a in temp.GetType().GetProperties())
{
   object firstParam = "PropOne";
   object secondParam = "PropTwo";
   AnotherCollection.Add(new MyClass() { PropOne = a.GetValue(firstParam), PropTwo = a.GetValue(PropTwo) });
}

但是它给了我以下编译错误。

  

无法将类型'object'隐式转换为'string'。存在显式转换(您是否错过了演员?)

有人可以帮我解决吗?

1 个答案:

答案 0 :(得分:2)

您必须将返回的对象从GetValue转换为string。编译器不知道从object返回的GetValue实际上是string,所以你必须告诉它这样。

此外,您必须传入您尝试获取(在这种情况下为temp)的值的实例:

PropOne = (string)a.GetValue(temp)