code

속성 설정자가 공용인지 확인하는 방법

codestyles 2021. 1. 6. 08:23
반응형

속성 설정자가 공용인지 확인하는 방법


PropertyInfo 객체가 주어지면 속성의 setter가 public인지 어떻게 확인할 수 있습니까?


무엇을 반환하는지 확인하십시오 GetSetMethod.

MethodInfo setMethod = propInfo.GetSetMethod();

if (setMethod == null)
{
    // The setter doesn't exist or isn't public.
}

또는 Richard의 대답 에 다른 스핀을 넣으려면 :

if (propInfo.CanWrite && propInfo.GetSetMethod(/*nonPublic*/ true).IsPublic)
{
    // The setter exists and is public.
}

setter가있는 한 속성을 설정하기 만하면됩니다. 실제로 setter가 퍼블릭인지 여부는 신경 쓸 필요가 없습니다. 공개 또는 비공개로 사용할 수 있습니다 .

// This will give you the setter, whatever its accessibility,
// assuming it exists.
MethodInfo setter = propInfo.GetSetMethod(/*nonPublic*/ true);

if (setter != null)
{
    // Just be aware that you're kind of being sneaky here.
    setter.Invoke(target, new object[] { value });
}

.NET 속성은 실제로 get 및 set 메서드를 감싸는 셸입니다.

GetSetMethodPropertyInfo 에서 메서드를 사용 하여 setter를 참조하는 MethodInfo를 반환 할 수 있습니다 . 을 사용하여 동일한 작업을 수행 할 수 있습니다 GetGetMethod.

이 메소드는 getter / setter가 비공개 인 경우 null을 반환합니다.

여기에 올바른 코드는 다음과 같습니다.

bool IsPublic = propertyInfo.GetSetMethod() != null;

public class Program
{
    class Foo
    {
        public string Bar { get; private set; }
    }

    static void Main(string[] args)
    {
        var prop = typeof(Foo).GetProperty("Bar");
        if (prop != null)
        {
            // The property exists
            var setter = prop.GetSetMethod(true);
            if (setter != null)
            {
                // There's a setter
                Console.WriteLine(setter.IsPublic);
            }
        }
    }
}

You need to use the underling method to determine accessibility, using PropertyInfo.GetGetMethod() or PropertyInfo.GetSetMethod().

// Get a PropertyInfo instance...
var info = typeof(string).GetProperty ("Length");

// Then use the get method or the set method to determine accessibility
var isPublic = (info.GetGetMethod(true) ?? info.GetSetMethod(true)).IsPublic;

Note, however, that the getter & setter may have different accessibilities, e.g.:

class Demo {
    public string Foo {/* public/* get; protected set; }
}

So you can't assume that the getter and the setter will have the same visibility.

ReferenceURL : https://stackoverflow.com/questions/3762456/how-to-check-if-property-setter-is-public

반응형