C#,.NET 3.5你如何找到只有getter和setter的屬性?
我想獲得一個對象的所有屬性,該對象具有一個getter和一個setter實例。該代碼我認爲要工作
PropertyInfo[] infos = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty);
然而,結果包括不具有制定者的屬性。給你我的繼承結構的一個簡單的想法,可能會影響這個(雖然我不知道如何):
public interface IModel
{
string Name { get; }
}
public class BaseModel<TType> : IModel
{
public virtual string Name { get { return "Foo"; } }
public void ReflectionCopyTo(TType target)
{
PropertyInfo[] infos = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty);
foreach (PropertyInfo info in infos)
info.SetValue(target, info.GetValue(this, null), null);
}
}
public class Child : BaseModel<Child>
{
// I do nothing to override the Name property here
}
與名稱工作時,我結束了以下錯誤:
System.ArgumentException: Property set method not found.
編輯:我想知道爲什麼不是工作,以及我應該怎麼做才能得到錯誤。
但爲什麼不BindingFlags.SetProperty已經這樣做篩選?這就是我認爲應該做的。 – Matt 2008-11-19 16:32:40
@Matt:因爲BindingFlags.SetProperty和BindingFlags.SetProperty不用於查找,所以在其他情況下使用它們,Get Properties()方法忽略這些標誌。嘗試沒有它們,您將得到相同的結果。請參閱支持的標誌:http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx – 2008-11-19 16:51:25