Reflection属性信息:如何在运行时仅显示一些属性 [英] Reflection Property Info :How to show only some Properties at runtime
本文介绍了Reflection属性信息:如何在运行时仅显示一些属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码:
my code:
namespace Reflection
{
class Program
{
static void Main(string[] args)
{
Type t = typeof(Product);
PropertyInfo[] proInfo = t.GetProperties();
foreach (var item in proInfo)
{
Console.WriteLine(item.Name);
}
}
}
public class Product
{
public int ProId { get; set; }
public string ProName { get; set; }
public string Description { get; set; }
public decimal UnitPrice { get; set; }
}
}
我得到所有属性名称作为输出。但我不想在输出中显示ProId和Decription。我怎么能这样做????
I get all properties names as output.But I dont want to show ProId and Decription in the output .How can i do that????
推荐答案
根据您的需要,另一种方法可能是使用BrowsableAttribute:
Depending on your needs another approach could be to use the BrowsableAttribute:
public class Product
{
[Browsable(false)]
public int ProId { get; set; }
public string ProName { get; set; }
public string Description { get; set; }
[Browsable(false)]
public decimal UnitPrice { get; set; }
}
Type t = typeof(Product);
PropertyInfo[] proInfo = t.GetProperties();
foreach (var pi in proInfo)
{
object [] att = pi.GetCustomAttributes(typeof(BrowsableAttribute), false);
if (att.Length > 0)
{
BrowsableAttribute b = att[0] as BrowsableAttribute;
if (b.Browsable)
{
Console.WriteLine(item.Name);
}
}
}
你不能追溯隐藏反映的公共财产 - 它无论如何都要检索它们。
当您定义访问修饰符以限制可用性时,您可以做的是更改访问修饰符:
You can''t retrospectively hide public properties from reflection - it retrieves them regardless.
What you can do is change the access modifiers when you define them to restrict the availability:
public class Product
{
protected int ProId { get; set; }
public string ProName { get; set; }
internal string Description { get; set; }
public decimal UnitPrice { get; set; }
}
会隐藏属性。
Would hide the properties for you.
这篇关于Reflection属性信息:如何在运行时仅显示一些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文