如何取回自定义属性?

How to Get Custom Attribute Back?

说我有这个 属性 具有这个属性

[StringLength(3)]
public string Owner { get; set; }

我如何使用反射让我回来

"[StringLength(3)]"

我不在乎它是作为字符串返回还是我是否必须重建它,但我希望得到我可以访问的结果。

假设您的 class 被称为 Test 并且 属性 被称为 Owner:

,这应该足以让您继续前进
var attributeStrings = typeof(Test)
    .GetProperty("Owner")
    .CustomAttributes   
    .Select(a => 
        string.Format(
            "[{0}({1})]",
            a.AttributeType.Name.Replace("Attribute",""),
            string.Join(", ", a.ConstructorArguments.Select(ca => ca.Value))
));