c# - 创建无参数属性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; }
解决方案
属性不做任何事情。它们是元数据——除非您查询属性模型的元数据,或者您正在使用某些 IL 重写工具,否则它们不会处于活动状态。请注意,属性不能直接访问它所在的上下文 - 为此,您需要向属性添加方法,并在物化属性上调用这些方法,并传入任何所需的上下文。
仅当您通过反射 API 请求时才会创建属性的对象实例(并且:每次查询时它都会为您提供完全不同的实例)。在那之前,它只是作为元数据存在。
推荐阅读
- html - 输入不适合 div
- javascript - react-redux 中的 onclick 事件触发
- python - Python脚本调用正确完成但仍作为正在运行的进程的外部程序?
- pandas - 如何在给定的数据框中仅添加索引列
- java - 你如何在 Java 中使用 PerspectiveAPI?
- python - VSCode Python 3+ Microsoft 扩展不会警告传入不同类型的参数
- python-3.x - “tensorflow.python.framework.errors_impl.FailedPreconditionError”同时运行“model_main_tf2.py”以在 tensorflow 中训练对象检测模型
- c - 代码运行没有错误或警告,但它崩溃
- unity3d - Unity Build 以混合现实为目标,但未出现在应用程序中
- c - C 编程 - 进程以状态 -1073741510 终止