閱讀

2016-01-21 69 views
0

我有2類閱讀

1類

public class baseClass 
{ 
    public string prop1{get;set;} 
    public string prop2{get;set;} 
    public string prop3{get;set;} 
} 

2類

public class derived:baseClass 
{ 
    public string prop4{get;set;} 
} 

的派生屬性以及基類現在,當我嘗試用下面的代碼來讀取性能,但如其顯而易見的是它只返回派生類的屬性

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(derived)); 

有沒有用,我可以讀出的派生屬性以及基類

+1

的[TypeDescriptor不從繼承的接口返回會員]可能的複製(http://stackoverflow.com/questions/ 4031267/typedescriptor-doesnt-return-members-from-inherited-interfaces) – Steve

+1

但是這對我有用,並返回基本屬性和派生屬性!只有一個人認爲類名的'base'是無效的。你應該選擇另一個名字。 –

+0

在C#中,你的類甚至可以編譯?因爲'base'不是有效的類名。 – Irshad

回答

2

爲什麼不使用反射

PropertyInfo[] properties = typeof(derived).GetProperties(BindingFlags.Public | BindingFlags.Instance); 

    Console.Write(String.Join(Envrironment.NewLine, properties.Select(p => p.Name))); 
1

任何方式其實它的工作原理:

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(Derived)); 

for (int i = 0; i < properties.Count; i++) 
{ 
    Console.WriteLine(properties[i].Name); 
} 

返回:

PROP1 PROP2 prop3 prop4

而正如我在http://referencesource.microsoft.com/中創建的,GetProperties()將在內部呼叫GetProviderRecursive

/// <devdoc> 
///  This method returns a type description provider, but instead of creating 
///  a delegating provider for the type, this will walk all base types until 
///  it locates a provider. The provider returned cannot be cached. This 
///  method is used by the DelegatingTypeDescriptionProvider to efficiently 
///  locate the provider to delegate to. 
/// </devdoc> 
internal static TypeDescriptionProvider GetProviderRecursive(Type type) { 
    return NodeFor(type, false);  
} 

我不知道你想取得屬性的目的是什麼,但作爲@Dmitry Bychenko回答,您可以使用Reflection。您可以在SO link中查看兩種方式的區別。

更新到你的答案:

var result = typeof(Derived).GetProperties() 
       .Select(prop => new 
       { 
        prop.Name, 
        prop.PropertyType 
       }); 
+0

您是否使用「PropertyDescriptorCollection」?你能發佈一個完整的例子嗎?因爲當我嘗試,但只有一個屬性 –

+0

@MARKANDBhatt是的,我用你的代碼。 –

+0

@MARKANDBhatt你使用的是.net版本嗎? –

0

我找到解決方案,讀取屬性的名稱以及它的類型

var properties = typeof(T).GetFields(); 
foreach (var prop in properties) 
{ 
    var name = prop.Name; 
    var type = Nullable.GetUnderlyingType(prop.FieldType.FullName) ?? prop.FieldType.FullName); 
}