在C#中通过反射,我们可以获得具有特定数据类型的所有声明属性。 [英] In C# through reflection can we get all declared properties with specific data types.

查看:587
本文介绍了在C#中通过反射,我们可以获得具有特定数据类型的所有声明属性。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,通过反射将获得整个声明的属性和方法等。但我担心的是,我们只能获得该类中所有声明属性的特定数据类型。请仔细阅读下面的示例代码,了解我想要的内容。

In C# through the reflection will get entire declared properties and methods etc. But my concern is can we get only specific datatype for all declared properties in that class. please go through the below sample code will get idea what I want exactly.

公共课客户

{

 公众客户()

  {//默认构造函数}

public class Customer
{
  public Customer()
  {//Default constructor }

  public int Id {get; set;}

  public string FirstName {get; set;}

  public string LastName {get; set;}

  public string Address {get; set;}

  public bool Validate(Customer customerObj)

  {//验证客户对象的代码

   返回true;

  } b $ b}

  public int Id {get; set;}
  public string FirstName{ get; set;}
  public string LastName{get; set;}
  public string Address{get; set;}
  public bool Validate(Customer customerObj)
  {//Code to validate the customer object
    return true;
  }
}

在上面的代码中,我们只想获取字符串数据类型所有属性,在此类中,类似方式只会得到int等。同样,我们希望通过反射获取用户定义以及构建所有数据类型。

In the above code we want to get only string datatype all properties in this class, like way will get only int also etc., same way we want to fetch User Defined as well as in build all data types through the reflection.

推荐答案

您可以尝试这样的事情:

You can try something like this:

var customerType = typeof(Customer);

var stringProperties = customerType.GetProperties().Where(p => p.PropertyType == typeof(string));

var intProperties = customerType.GetProperties().Where(p => p.PropertyType == typeof(int));

foreach (var property in stringProperties)
    Console.WriteLine(


" string property:{property.Name}");

foreach(intProperties中的var属性)
Console.WriteLine(
"string property: {property.Name}"); foreach (var property in intProperties) Console.WriteLine(


" int property:{property.Name}");
"int property: {property.Name}");


这篇关于在C#中通过反射,我们可以获得具有特定数据类型的所有声明属性。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆