باستخدام الانعكاس تعيين خاصية من خاصية كائن

StackOverflow https://stackoverflow.com/questions/1402479

  •  05-07-2019
  •  | 
  •  

سؤال

ولقد حصلت على فئتين.

public class Class1 {
   public string value {get;set;}
}

public class Class2 {
   public Class1 myClass1Object {get;set;}
}

ولقد حصلت كائن من نوع CLASS2. أنا بحاجة إلى استخدام التفكير في CLASS2 لتعيين الخاصية قيمة ... أي بمعنى، لو كنت أفعل ذلك دون تفكير، هذه هي الطريقة التي أود أن تذهب عنه:

Class2 myObject = new Class2();
myObject.myClass1Object.value = "some value";

هل هناك طريقة للقيام أعلاه، في حين تستخدم انعكاس للوصول إلى خاصية "myClass1Object.value"؟

وشكرا مقدما.

هل كانت مفيدة؟

المحلول

وتقسيم أساسا الى قسمين الملكية الوصول. أولا عليك <م> الحصول على الممتلكات myClass1Object، فإنك <م> تحديد الممتلكات value على النتيجة.

من الواضح أنك سوف تحتاج إلى أن تأخذ أيا كان الشكل الذي قد حصلت على اسم الخاصية في وتقسيمه من - على سبيل المثال من النقاط. على سبيل المثال، وهذا ينبغي القيام عمق التعسفي من خصائص:

public void SetProperty(object source, string property, object target)
{
    string[] bits = property.Split('.');
    for (int i=0; i < bits.Length - 1; i++)
    {
         PropertyInfo prop = source.GetType().GetProperty(bits[i]);
         source = prop.GetValue(source, null);
    }
    PropertyInfo propertyToSet = source.GetType()
                                       .GetProperty(bits[bits.Length-1]);
    propertyToSet.SetValue(source, target, null);
}

وباعتراف الجميع عليك ربما تريد أكثر قليلا خطأ التحقق من ذلك:)

نصائح أخرى

وكنت أبحث عن أجوبة لهذه القضية حيث أن الحصول على قيمة العقار، وعندما يتم إعطاء اسم الخاصية، لكن من غير المعروف على مستوى التعشيش للممتلكات.

وعلى سبيل المثال. إذا كان الإدخال "قيمة" بدلا من توفير اسم الخاصية مؤهل بشكل كامل مثل "myClass1Object.value".

وألهم إجاباتك حل بي عودي أدناه:

public static object GetPropertyValue(object source, string property)
{
    PropertyInfo prop = source.GetType().GetProperty(property);
    if(prop == null)
    {
      foreach(PropertyInfo propertyMember in source.GetType().GetProperties())
      { 
         object newSource = propertyMember.GetValue(source, null);
         return GetPropertyValue(newSource, property);
      }
    }
    else
    {
       return prop.GetValue(source,null);
    }
    return null;
}
   public static object GetNestedPropertyValue(object source, string property)
    {
        PropertyInfo prop = null;
        string[] props = property.Split('.');

        for (int i = 0; i < props.Length; i++)
        {
            prop = source.GetType().GetProperty(props[i]);
            source = prop.GetValue(source, null);
        }
        return source;
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top