【发布时间】:2017-01-22 17:05:33
【问题描述】:
给定以下代码:
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Xunit;
namespace Company.Tests
{
public class MyObject
{
[Display(Order = 1000)]
public virtual string StringPropertyB { get; set; }
[Display(Order = 2000)]
public virtual string StringPropertyA { get; set; }
}
public class MyObjectTest
{
[Fact]
public void X()
{
var properties = typeof(MyObject).GetProperties();
var stringPropertyBPropertyInfo = properties[0];
var stringPropertyAPropertyInfo = properties[1];
// Debugger Display = "{[System.ComponentModel.DataAnnotations.DisplayAttribute(Order = 1000)]}"
var bDisplayAttribute = stringPropertyBPropertyInfo.GetCustomAttributesData().FirstOrDefault();
// Debugger Display = "{[System.ComponentModel.DataAnnotations.DisplayAttribute(Order = 2000)]}"
var aDisplayAttribute = stringPropertyAPropertyInfo.GetCustomAttributesData().FirstOrDefault();
}
}
}
如何以编程方式更新 Order 属性?
我想在它设置为新值后对其进行更新。 (用例不必指定 Order,而是自动为 Order 分配一个值,以匹配 MyObject 上的属性从上到下出现的顺序。)
【问题讨论】:
-
如果您需要更改它,我想您可能只想将其存储在一个属性中。
-
我可能错了,但在我看来,在运行时修改属性似乎会破坏范式。如果我是你,我会以其他方式重新排列你的属性。
-
但是我已经很接近了... :) 一直在尝试...
var property = cad.AttributeType.GetProperty("Order"); property.SetValue(whatToUseHere, 30000);只是想不通whatToUseHere 应该使用什么 -
这可能有助于为您指明正确的方向:stackoverflow.com/questions/2160476/… 我也知道您可以在运行时使用反射访问属性: public static object GetAttribute(object parent, Type attributeType) { var property = parent .GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, attributeType)).Single(); var 属性 = property.GetCustomAttribute(attributeType);返回属性; }
-
另外,你也可以检查对象是否有一个私有的“set”值......如果我今天晚些时候有时间,并且没有其他人弄清楚,我会一起扔一些东西看看我能不能给你POC。
标签: c# reflection