gru*_*ber 5 .net c# reflection
我编写了自定义属性属性并将其设置在我的类中的几个属性上.现在我想在运行时只获取具有此属性的属性,能够获取属性的值以及属性字段的值.你能帮我完成这项任务吗?感谢帮助
Tim*_* S. 14
这是一个例子:
void Main()
{
var myC = new C { Abc = "Hello!" };
var t = typeof(C);
foreach (var prop in t.GetProperties())
{
var attr = prop.GetCustomAttributes(typeof(StringLengthAttribute), true).Cast<StringLengthAttribute>().FirstOrDefault();
if (attr != null)
{
var attrValue = attr.MaximumLength; // 100
var propertyValue = prop.GetValue(myC, null); // "Hello!"
}
}
}
class C
{
[StringLength(100)]
public string Abc {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15142 次 |
| 最近记录: |