首页 > 解决方案 > 创建无参数属性c#

问题描述

我正在尝试创建一个读取字符串属性的属性,做一些工作并替换它。

如何从属性访问属性?

属性:

[AttributeUsage(AttributeTargets.Property)]
public class CustomAttribute : Attribute
{
    public CustomAttribute()
    {
        //get the property value
        //propertyValue = propertyValue + "!";
        //set the property value to be the updated propertyValue;

        //how do i get the value of the property the attribute is added to and modify it?
    }
}

用法:

[CustomAttribute]
public string MyProperty { get; set; }

标签: c#custom-attributes

解决方案


属性不做任何事情。它们是元数据——除非您查询属性模型的元数据,或者您正在使用某些 IL 重写工具,否则它们不会处于活动状态。请注意,属性不能直接访问它所在的上下文 - 为此,您需要向属性添加方法,并在物化属性上调用这些方法,并传入任何所需的上下文。

仅当您通过反射 API 请求时才会创建属性的对象实例(并且:每次查询时它都会为您提供完全不同的实例)。在那之前,它只是作为元数据存在。


推荐阅读