搜索类中所有字符串类型成员(包括搜索类类型中的属性)C# [英] Search all the string type member in a class(including searching the property in class type) C#
问题描述
我试图从一个类中找出所有字符串"类型的属性,但想知道如果这个类中有任何类类型属性,我该怎么做.
I tried to find out all the "string" type properties from a class, but wonder how can I do that if there is any class type property in this class.
以下代码显示了目标类和我的解决方案.
The following codes show the target class and my solution.
public class Credit_Card
{
public string brand { get; set; }
public string billing_phone { get; set; }
public Expiration expiration { get; set; }
}
public class Expiration
{
public string month { get; set; }
}
class program
{
static void Main(string[] args)
{
foreach (PropertyInfo prop in typeof(Credit_Card).GetProperties())
{
if(prop.PropertyType == typeof(string))
{
Console.WriteLine(prop.Name);
}
}
Console.ReadLine();
}
}
我的Main"方法只能在 Credit_Card 类型中显示brand"和billing_phone"属性,而在过期类中缺少month"属性.
My "Main" method can only show "brand" and "billing_phone" properties in Credit_Card type, but missed "month" property in expiration class.
有什么办法可以在 Credit_Card 类中进行递归搜索?
Is there any way that I can do recursive search in Credit_Card class?
推荐答案
public static void Main (string[] args)
{
foreach(PropertyInfo prop in GetStringProperties(typeof(Credit_Card)))
Console.WriteLine(prop.Name);
Console.ReadLine();
}
public static IEnumerable<PropertyInfo> GetStringProperties(Type type)
{
return GetStringProperties (type, new HashSet<Type> ());
}
public static IEnumerable<PropertyInfo> GetStringProperties(Type type, HashSet<Type> alreadySeen)
{
foreach(var prop in type.GetProperties())
{
var propType = prop.PropertyType;
if (propType == typeof(string))
yield return prop;
else if(alreadySeen.Add(propType))
foreach(var indirectProp in GetStringProperties(propType, alreadySeen))
yield return indirectProp;
}
}
捕捉我们已经处理过的类型很重要,否则你可以很容易地进入无限循环,因为这采用递归方法,它会因 StackOverflowException
而崩溃,而不仅仅是挂起永远像迭代等价物一样.(唯一比抛出异常更糟糕的情况是不抛出异常).
It's important to catch types we've already processed, or you can easily get into an infinite loop with the small mercy that since this takes a recursive approach it crashes with a StackOverflowException
rather than just hanging forever like the iterative equivalent would. (Another case of the only thing worse than throwing an exception is no throwing an exception).
这篇关于搜索类中所有字符串类型成员(包括搜索类类型中的属性)C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!