可以使用反射和属性来实现动态更改属性的属性。以下是一个代码示例,可以在控制器的操作方法中使用:
using System.Reflection;
public ActionResult MyAction()
{
// 获取属性的类型和名称
Type attributeType = typeof(MyAttribute);
string propertyName = "MyProperty";
// 获取当前属性值
MyAttribute attribute = (MyAttribute)ControllerContext
.MethodInfo.GetCustomAttribute(attributeType);
string currentValue = attribute.GetType()
.GetProperty(propertyName).GetValue(attribute).ToString();
// 更改属性值
string newValue = "new value";
attribute.GetType().GetProperty(propertyName)
.SetValue(attribute, newValue);
return View();
}
[My("original value")]
public class MyController : Controller
{
// ...
}
public class MyAttribute : Attribute
{
public string MyProperty { get; set; }
public MyAttribute(string myProperty)
{
MyProperty = myProperty;
}
}
在此示例中,我们获取了控制器中设置的自定义属性(MyAttribute
),并获取了其名称(MyProperty
)和值(currentValue
)。然后,我们使用反射和属性,更改属性值为“新值”。最后,我们返回视图,显示更改后的属性值。