例如:将公司信息分类显示。
1.公司信息分为“基本信息”、“公司描述”。
public class CompanyInfo
{[Describute("基本信息", true, "公司名称")]
public string Name { get; set; }
[Describute("基本信息",true,"成立时间")]
public string Foundtion {get;set;}
[Describute("公司描述", true, "公司描述")]
public string OverView { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
public class Describute : Attribute
{
public string style { get; set; }
public bool show { get; set; }
public string content { get; set; }
/// <summary></summary>
/// <param name="style">父标签</param>
/// <param name="show">是否显示</param>
/// <param name="content">标签内容</param>
public Describute(string style, bool show, string content)
{
this.style = style;
this.show = show;
this.content = content;
}
}
2.根据不同类别获取对应的信息。
public void GetCompanyInfo()
{
CompanyInfo info = new CompanyInfo()
{
Name = "名称",
OverView = "公司简介"
};
foreach (System.Reflection.PropertyInfo p in info.GetType().GetProperties())
{
Describute describute = (Describute)(p.GetCustomAttributes(typeof(Describute), false))[0];
object pValue = p.GetValue(info, null);
string Info = string.Empty;
if (pValue != null) { Info = pValue.ToString().Replace(" ", string.Empty); }
if (string.IsNullOrEmpty(Info)) { Info = "暂无信息"; }
string valueStr = describute.content == string.Empty ? Info : describute.content + ":" + Info ; //格式(描述:值)
switch (describute.style)
{
case "基本信息":
//TODO:获取基本信息:公司名称、成立时间
break;case "公司描述":
//TODO:获取公司描述
break;default:
break;
}
}
}