簡體   English   中英

如何檢查屬性設置器是否是公共的

[英]How to check if property setter is public

給定一個 PropertyInfo 對象,如何檢查該屬性的 setter 是否是公共的?

檢查您從GetSetMethod返回的GetSetMethod

MethodInfo setMethod = propInfo.GetSetMethod();

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

或者,換個角度看理查德的回答

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 方法的包裝外殼。

您可以在 PropertyInfo 上使用GetSetMethod方法,返回引用 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);
            }
        }
    }
}

您需要使用底層方法來確定可訪問性,使用PropertyInfo.GetGetMethod()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;

但是請注意,getter 和 setter 可能具有不同的可訪問性,例如:

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

所以你不能假設 getter 和 setter 將具有相同的可見性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM