Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 读取派生类和基类的属性_C# - Fatal编程技术网

C# 读取派生类和基类的属性

C# 读取派生类和基类的属性,c#,C#,我有两门课 第一类 public class baseClass { public string prop1{get;set;} public string prop2{get;set;} public string prop3{get;set;} } 第二类 public class derived:baseClass { public string prop4{get;set;} } 现在,当我尝试用下面的代码读取属性时,很明显,它只返回派生类的属性 Prope

我有两门课

第一类

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

public class derived:baseClass
{
    public string prop4{get;set;}
}
现在,当我尝试用下面的代码读取属性时,很明显,它只返回派生类的属性

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(derived));
是否有任何方法可以读取派生类和基类的属性?实际上,它可以工作:

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

for (int i = 0; i < properties.Count; i++)
{
     Console.WriteLine(properties[i].Name);
}
我不知道您试图获取属性的目的是什么,但正如@Dmitry Bychenko回答的那样,您可以使用
反射
。您可以在这里检查这两种方法的差异

更新您的答案:

实际上它是有效的:

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

for (int i = 0; i < properties.Count; i++)
{
     Console.WriteLine(properties[i].Name);
}
我不知道您试图获取属性的目的是什么,但正如@Dmitry Bychenko回答的那样,您可以使用
反射
。您可以在这里检查这两种方法的差异

更新您的答案:

为什么不使用反射

为什么不使用反射


我找到了读取属性名及其类型的解决方案

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

我找到了读取属性名及其类型的解决方案

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

可能重复,但这对我有效,并返回基本属性和派生属性!只有一个人认为类名的
base
无效。你应该选择另一个名字。在C中,你的类甚至编译过?因为
base
不是有效的类名。的可能重复,但这对我有效,并返回基属性和派生属性!只有一个人认为类名的
base
无效。你应该选择另一个名字。在C中,你的类甚至编译过?因为
base
不是有效的类名。是否使用了“PropertyDescriptorCollection”?你能举一个完整的例子吗。因为当我试过但只得到一个property@MARKANDBhatt您使用的是哪个
.net
版本?@MARKANDBhatt您确定所有项目都是
公共的
?您是否使用了“PropertyDescriptorCollection”?你能举一个完整的例子吗。因为当我试过但只得到一个property@MARKANDBhatt您使用的是哪个
.net
版本?@MARKANDBhatt您确定所有项目都是
公共的
?问题可能是基本接口而不是基类?问题可能是基本接口而不是基类?
var properties = typeof(T).GetFields();
foreach (var prop in properties)
{
  var name =  prop.Name;
  var type = Nullable.GetUnderlyingType(prop.FieldType.FullName) ?? prop.FieldType.FullName);
}