>  기사  >  백엔드 개발  >  C#에서는 리플렉션을 사용하여 읽기 전용 속성에 값을 할당할 수 있나요?

C#에서는 리플렉션을 사용하여 읽기 전용 속성에 값을 할당할 수 있나요?

黄舟
黄舟원래의
2017-02-17 10:54:511629검색

결론:

다음과 같이 데모를 확인할 수 있습니다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace IconTest
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            ReflectTest rt = new ReflectTest();
            rt.GetType().GetProperty("ID").SetValue(rt, "Guid", null);
            MessageBox.Show(rt.ID);
        }

    }
    public class ReflectTest
    {
        private string id;
        [ReadOnly(true)]
        public string ID
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }
    }
}


winform 프로그램 출력 실행:



작은 메모:

TypeDescriptor.GetProperties는 값을 설정하는 데 사용되며 효과가 없습니다.

TypeDescriptor.GetProperties(rt)["ID"].SetValue(rt, "Guid");

그렇다면 TypeDescriptor.GetProperties는 왜 setvalue가 효과가 없는 이유를 사용합니까?

위 코드를 다음 두 문장으로 나눕니다.

PropertyDescriptor prop = TypeDescriptor.GetProperties(rt)["ID"];
prop.SetValue(rt, "Guid");

단일 지점 추적 들어가서 다음을 찾을 수 있습니다:



추상 클래스 PropertyDescriptor의 인스턴스를 얻은 후, SetValue 메서드가 호출되면 하위 클래스 ReflectPropertyDescriptor에서 호출됩니다.



특히 구현은 하위 클래스인 ReflectPropertyDescriptor에 있습니다. Microsoft 소스 코드에서 ReflectPropertyDescriptor 및 SetValue

를 찾으세요. 코드, 읽기 전용 속성은 직접 건너뜁니다. . . . . .

그럼 PropertyInfo에는 제한이 있나요?

PropertyInfo에서 호출하는 SetValue는 다음과 같습니다.


구체적인 구현은 다음과 같이 Microsoft의 오픈 소스 코드에서 찾을 수 있습니다.

 public override void SetValue(object component, object value) {
#if DEBUG
            if (PropDescUsageSwitch.TraceVerbose) {
                string compName = "(null)";
                string valName  = "(null)";

                if (component != null)
                    compName = component.ToString();
                if (value != null)
                    valName = value.ToString();

                Debug.WriteLine("[" + Name + "]: SetValue(" + compName + ", " + valName + ")");
            }
#endif
            if (component != null) {
                ISite site = GetSite(component);
                IComponentChangeService changeService = null;
                object oldValue = null;

                object invokee = GetInvocationTarget(componentClass, component);

                Debug.Assert(!IsReadOnly, "SetValue attempted on read-only property [" + Name + "]");
                if (!IsReadOnly) {

                    // Announce that we are about to change this component
                    //
                    if (site != null) {
                        changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
                        Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
                    }


                    // Make sure that it is ok to send the onchange events
                    //
                    if (changeService != null) {
                        oldValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null); 
                        try {
                            changeService.OnComponentChanging(component, this);
                        }
                        catch (CheckoutException coEx) {
                            if (coEx == CheckoutException.Canceled) {
                                return;
                            }
                            throw coEx;
                        }
                    }

                    try {
                        try {
                            SecurityUtils.MethodInfoInvoke(SetMethodValue, invokee, new object[] { value });
                            OnValueChanged(invokee, EventArgs.Empty);
                        }
                        catch (Exception t) {
                            // Give ourselves a chance to unwind properly before rethrowing the exception.
                            //
                            value = oldValue;
                            
                            // If there was a problem setting the controls property then we get:
                            // ArgumentException (from properties set method)
                            // ==> Becomes inner exception of TargetInvocationException
                            // ==> caught here

                            if (t is TargetInvocationException && t.InnerException != null) {
                                // Propagate the original exception up
                                throw t.InnerException;
                            }
                            else {
                                throw t;
                            }
                        }
                    }
                    finally {
                        // Now notify the change service that the change was successful.
                        //
                        if (changeService != null) {
                            changeService.OnComponentChanged(component, this, oldValue, value);
                        }
                    }
                }
            }
        }

아직
PropertyInfo 호출을 본 적이 없습니다. > SetValue


PropertyInfo.GetSetMethod 메서드(부울)


위는 C#에서 읽기 전용 속성에 값을 할당할 수 있나요? 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 주목해주세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.