gpt4 book ai didi

c# - 如何以编程方式更新 DisplayAttribute 上的 Order 属性?

转载 作者:太空宇宙 更新时间:2023-11-03 12:39:40 26 4
gpt4 key购买 nike

给定以下代码:

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 属性?

我想在它设置为新值后更新它。 (用例不必指定订单,而是自动为订单分配一个值,以匹配 MyObject 上的属性从上到下出现的顺序。)

最佳答案

正如 Skeet 先生在 Thumper 指出的答案中所写,据我所知,这是无法完成的。您可以更新订单值,但它不会持续存在:

using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using Shouldly;
using Xunit;

namespace Tests
{
public class ObjectWithDisplayOrder
{
[Display(Order = 0)]
public virtual string StringPropertyB { get; set; }

[Display(Order = 0)]
public virtual string StringPropertyA { get; set; }
}

public class DisplayOrderTests
{
[Fact]
public void ShouldUpdateDisplayOrderProperty()
{
const int updatedOrderValue = 1000;

var properties = typeof(ObjectWithDisplayOrder).GetProperties();
foreach (var property in properties)
{
var displayAttribute = (DisplayAttribute) property.GetCustomAttributes().First(a => a is DisplayAttribute);
var props = displayAttribute.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).ToList();
props.Single(p => p.Name == "Order").SetValue(displayAttribute, updatedOrderValue);
// displayAttribute Order is 1000 here, but it's not persisted...
}

foreach (var property in properties)
{
var displayAttribute = (DisplayAttribute) property.GetCustomAttributes().First(a => a is DisplayAttribute);
displayAttribute.GetOrder().ShouldBe(updatedOrderValue); // Fails - Order is still 0
}
}
}
}

关于c# - 如何以编程方式更新 DisplayAttribute 上的 Order 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39498103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com