給定一個PropertyInfo對象,如何檢查該屬性的setter是否公開?如何檢查屬性設置器是否公開
45
A
回答
89
檢查你從GetSetMethod
回來:
MethodInfo setMethod = propInfo.GetSetMethod();
if (setMethod == null)
{
// The setter doesn't exist or isn't public.
}
或者,換一個不同的自旋Richard's answer:
if (propInfo.CanWrite && propInfo.GetSetMethod(/*nonPublic*/ true).IsPublic)
{
// The setter exists and is public.
}
注如果你想要做的只是設置一個屬性,只要它有一個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 });
}
9
.NET屬性實際上是get和set方法的一個包裝外殼。
您可以在PropertyInfo上使用GetSetMethod
方法,返回引用setter的MethodInfo。你可以用GetGetMethod
做同樣的事情。
如果getter/setter是非公開的,這些方法將返回null。這裏
正確的代碼是:
bool IsPublic = propertyInfo.GetSetMethod() != null;
4
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);
}
}
}
}
0
您需要使用的下屬方法來確定可訪問性,使用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;
但是請注意,吸氣劑&制定者可能有不同的通達性,例如:
class Demo {
public string Foo {/* public/* get; protected set; }
}
所以你不能假設的getter和二傳手將具有相同的知名度。
相關問題
- 1. Liquibase:檢查是否設置了屬性
- 2. Apache RewriteCondition:檢查屬性是否設置
- 3. 如何檢查外觀屬性是否已設置?
- 4. 如何檢查css屬性是否設置?
- 5. 如何檢查NAnt腳本是否設置屬性?
- 6. 如何打開XML屬性檢查器
- 7. 檢查是否已設置課程中的任何屬性
- 8. 如何檢查節點是否屬性
- 9. 檢查屬性是否具有屬性
- 10. 如何檢查cookie是否設置?
- 11. 如何檢查是否datatable.PrimaryKey設置
- 12. 如何檢查WaitHandle是否已設置?
- 13. 如何檢查LogWriter是否已設置?
- 14. 如何檢測是否只設置了部分屬性?
- 15. 檢查是否設置對象的包含與此屬性
- 16. 核心數據檢查是否從未設置屬性
- 17. Laravel檢查是否設置了動態屬性
- 18. 的PowerShell:檢查是否有一堆屬性的設置
- 19. 的Java:檢查是否屬性被設置爲int和Integer
- 20. Python Django檢查屬性是否存在或已設置
- 21. 檢查是否在Core Data中設置了屬性?
- 22. 檢查是否請求屬性被設置與jQuery
- 23. 檢查是否已在phing中設置了屬性
- 24. 檢查屬性是否在類中設置
- 25. 如何公開xaml屬性?
- 26. 檢查變量是否公開php
- 27. 如何檢查是否在JavaScript和PHP中設置了jQuery屬性?
- 28. 如何檢查一個屬性是否設置在一個結構中
- 29. 如何檢查是否在字段上設置了必需的屬性
- 30. 轉:如何檢查結構屬性是否明確設置爲零值?
+1:這比GetSetMethod()更好。IsPublic' :它也適用於屬性有* no * setter的情況。 – Ani 2010-09-21 16:42:10
謝謝@Dan Tao。這是最好的答案:upvoted! – 2010-09-21 16:53:48
謝謝@丹濤。 :) – 2012-07-17 06:32:52