如何给实体类中的字段增加额外的属性,然后利用反射读取该额外属性值

zkj513703929 2013-03-22 04:09:54
如何给实体类中的字段增加额外的属性,然后利用反射读取该额外属性值!

首先想到的是用attribute
如:
class Model{
string imgUrl;
[Attribute(...)]
public string ImgUrl{get;set;}
之类的,,既然没有提供,那就重写,怎么个重写法呢?

}
...全文
1106 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zkj513703929 2013-03-22
  • 打赏
  • 举报
回复
引用 7 楼 zkj513703929 的回复:
知道扩张,但是不知道怎么用,现在知道了,谢谢gxingmin,Joyhen,!
知道扩展
zkj513703929 2013-03-22
  • 打赏
  • 举报
回复
知道扩张,但是不知道怎么用,现在知道了,谢谢gxingmin,Joyhen,!
gxingmin 2013-03-22
  • 打赏
  • 举报
回复
你改这个PropertyMappingAttribute 类啊 public class PropertyMappingAttribute : Attribute { [Description("是否是额外属性"),DefaultValue(true)] public bool IsCondition { get;set; } public int Length{get;set;} //这样你定义的属性上就可以加Length=100了 }
zkj513703929 2013-03-22
  • 打赏
  • 举报
回复
引用 3 楼 gxingmin 的回复:
可以的,你可以重写一个Attribute类 如: C# code?123456789101112131415161718public class Model { string imgUrl; [PropertyMappingAttribute(IsCondition=true)] public string ImgUr……
如果我给这个字段增加个属性呢,比如我要把在数据库中该字段的长度给附加上: [长度=100] public string ImgUrl { get; set; }
gxingmin 2013-03-22
  • 打赏
  • 举报
回复
可以的,你可以重写一个Attribute类 如:
public class Model
    {
        string imgUrl;

        [PropertyMappingAttribute(IsCondition=true)]
        public string ImgUrl { get; set; }

    }

    //
    public class PropertyMappingAttribute : Attribute
	{
        [Description("是否是额外属性"),DefaultValue(true)]
		public bool IsCondition
		{
			get;set;
		}
    }
反射时可以通过PropertyMappingAttribute来判断
 Model m=new Model();

            PropertyInfo[] pis = m.GetType().GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                PropertyMappingAttribute []attr = (PropertyMappingAttribute[])pi.GetCustomAttributes(typeof(PropertyMappingAttribute),true);
                if (attr.Length != 0 && attr[0].IsCondition)
                {
                     //额外属性
                }
            }
zkj513703929 2013-03-22
  • 打赏
  • 举报
回复
引用 1 楼 bdmh 的回复:
Attribute是特性,不是属性,要搞清楚
我没有表达清楚,我是从在C#后台给元素增加属性时 T.Attribute.add("","")方式想的
bdmh 2013-03-22
  • 打赏
  • 举报
回复
Attribute是特性,不是属性,要搞清楚

62,073

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧