说我有这个属性的属性
[StringLength(3)]
public string Owner { get; set; }
我如何使用反射让我回来
"[StringLength(3)]"
我不在乎它是否以字符串形式返回,或者我是否必须重建它,但我希望得到我可以访问的结果。
答案 0 :(得分:4)
这应该是足够的代码让你开始,假设你的类被调用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))
));