引用反射对象 [英] Getting reference to reflection object

查看:71
本文介绍了引用反射对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



请考虑以下情形:

Hi,

Consider this scenario:

class A {
      public B {
          get; set;
      }
}

class B {
     public string name { get; set; }
}



现在,我想获得对A对象的B对象的引用.

所以我正在使用PropertyInfo类来获取它,但是通过pi = GetValue();
而且我假设不会返回引用,而是返回对象的副本,因为在将值设置为对象之后,它不会更新原始的Class A 对象.

这是完成工作的代码片段:



Now I want to get a reference to the B object of the A object.

So I am using PropertyInfo Class to get that but through pi = GetValue();
And that I assume doesn''t return the reference but a copy of the object since, after setting the value to the object, it doesn''t update the original Class A object.

Here is a code snippet that does the work:

      // _TargetObject is the original A object.
private void SyncFieldChanges(string changed_field_id)
{
     PropertyInfo so;
     PropertyInfo to;
     object lv;
     object tw = null;

     try
     {
         to = GetNestedProperty(ref _TargetObject, FindTargetPropertyId(changed_field_id),ref tw);
         so = this.GetType().GetProperty(changed_field_id);

         lv = so.GetValue(this, null);
         to.SetValue(tw, lv, null);
     }
     catch { }

}

PropertyInfo GetNestedProperty(ref object target_object, string nested_property,ref object obj_to_write)
{
     object to;
     string tmp = "";
     string[] np;
     PropertyInfo pi = null;

     obj_to_write = null;

     if(string.IsNullOrEmpty(nested_property)) { return null; }
     np = nested_property.Split('.');
     if (np == null || (np.Length < 2)) 
     {
          pi = target_object.GetType().GetProperty(nested_property);
//This is where the obj_to_write after final recursion is set            
          obj_to_write = target_object;
          return pi;
     }

     for (int i = 1; i < np.Length; i++)
     {
          pi = target_object.GetType().GetProperty(np[i - 1]);

  //CULPRIT - Since in the next recursion call the reference to the to object is passed and to is fetched through GetValue...
          to = pi.GetValue(target_object,null);

          for(int j = i; j < np.Length; j++)
          {
              tmp += np[j] + (j + 1 == np.Length ? "" : ".");
          }
          pi = GetNestedProperty(ref target_object, tmp,ref obj_to_write);
      }
            
   return pi;
}



//-该函数将PropertyInfo对象返回给嵌套属性,并且obj_to_write应该是最远的嵌套属性之前的对象,obj_to_write应该指向A对象内的B对象,并且这样做,但是我认为罪魁祸首在上方(标记为"CULPRIT":D),因为pi.GetValue返回的是对象的值,而不是对该对象的引用(假设).
此函数是递归的,因此可能有点难以理解...



//--The function returns PropertyInfo object to the nested property, and obj_to_write should be the object just before the farthest nested property, the obj_to_write should point to B object inside A object, and it does that but I think the culprit is above (marked ''CULPRIT'' :D) because pi.GetValue returns an object''s value not a reference to that object (assumption).
This function is recursive so it might be a little hard to understand...

//--This i just helper function for locating property names  
private string FindTargetPropertyId(string key)
{
     string rv = "";
     KeyValuePair&lt;string, string&gt; kvp;
     kvp = FieldLinks.Find(delegate(KeyValuePair&lt;string, string&gt; o) { return o.Key == key; });
     rv = kvp.Value;
     return rv;
}





Any ideas how to get a reference to an object?

推荐答案

我真的有一段时间解码您的代码,可以这么说,您是任何人的c ++开发人员吗?机会吗?

无论如何,我认为您的算法本身已经失控了.假设您传递像这样的属性名称"Property1.SubProperty2.Subproperty3",我认为您需要这样的内容:


I''ve really had a time decoding your code so to speak, are you a c++ developer by any chance?

Anyway, I think your algorithm has run-away with itself. Assuming you pass the property name like this "Property1.SubProperty2.Subproperty3", I think you need something like this:


public object FindValue(object rootObject, string properties)
{
  
  List<string> propertyNames = new List <string>(string.Split("."));
  if(string.Length == 0)
    return null;
  return GetValue(rootObject, propertyNames);

}

public object GetValue(object currentObject, List<string>propertyNames)
{
    if(object == null)
     return null;
    if(propertyNames.Count == 0)
     return currentObject;
    PropertyInfo propertyInfo = currentObject.GetType().GetProperty(propertyNames[0]);
    if(propertyInfo == null)
        return null;
    propertyNames.RemoveAt(0);
    object nextObject= propertyInfo.GetValue(currentObject, null);
    return GetValue(nextObject, propertyNames); 
}



免责声明:我尚未测试我的代码&到这里来晚了,这段代码可能不是最佳的,我认为它会使迭代超出严格的要求!
propertyInfo.GetValue(currentObject, null)仅适用于非索引值.



Disclaimer: I haven''t tested my code & it''s getting late here, this code might not be optimal, I think it makes one more iteration than it strictly needs!
propertyInfo.GetValue(currentObject, null) only works for non-indexed values.


感谢Keith,

好吧,我不是C ++开发人员(过去是:)开发微控制器嵌入式软件)

谢谢您的回答,尽管我找到了真正的罪魁祸首...

我只是没看到...

我正在将结构传递给我的代码,当然,作为值类型的结构以这种方式不可反映...

实际上,我的代码从一开始就在工作,仅用于引用类型...

不管怎么说,还是要谢谢你! :)
Thanks Keith,

Well I''m not not a C++ developer (used to be :) developing micro-controller embedded software)

Thank you for your answer although, I have found out the real culprit...

I just didn''t see it...

I was passing a structure to my code, and of course structure being a value type is unreflectable in this way...

Actually my code was working from the beginning, just for reference types...

Thanks anyway! :)


这篇关于引用反射对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆