我有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));
有什么方法可以读取派生属性和基类
答案 0 :(得分:2)
为什么不使用 Reflection ?
<div class="wrapper">
<div class="container">
<h1>Welcome</h1>
<form class="form">
<input type="text" placeholder="name">
<input type="contact" placeholder="contact number">
<input type="add" placeholder="Country">
<input type="Bday" placeholder="Birthday">
<input type="Age" placeholder="Age">
<input type="pin" placeholder="Pin number">
<button type="submit" id="sign">Sign-up</button>
</form>
</div>
</div>
答案 1 :(得分: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
});
答案 2 :(得分: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);
}