我正在开发一个使用某些属性标记的框架。这将在 MVC 项目中使用,并且大约每次我在 View 中查看特定记录时都会发生(例如/Details/5)
我想知道是否有更好/更有效的方法或最佳实践示例。
无论如何,我有几个属性,例如:
[Foo("someValueHere")]
String Name {get;set;}
[Bar("SomeOtherValue"]
String Address {get;set;}
寻找这些属性/根据它们的值采取行动的最有效方法/最佳实践是什么?
我目前正在做这样的事情:
[System.AttributeUsage(AttributeTargets.Property)]
class FooAttribute : Attribute
{
public string Target { get; set; }
public FooAttribute(string target)
{
Target = target;
}
}
在我对这些属性进行操作的方法中(简化示例!):
public static void DoSomething(object source)
{
//is it faster if I make this a generic function and get the tpe from T?
Type sourceType = source.GetType();
//get all of the properties marked up with a foo attribute
var fooProperties = sourceType
.GetProperties()
.Where(p => p.GetCustomAttributes(typeof(FooAttribute), true)
.Any())
.ToList();
//go through each fooproperty and try to get the value set
foreach (var prop in fooProperties)
{
object value = prop.GetValue(source, null);
// do something with the value
prop.SetValue(source, my-modified-value, null);
}
}
最佳答案
Attribute.GetCustomAttribute
和 PropertyInfo
/MemberInfo.GetCustomAttribute
是获取属性对象的推荐方式。
虽然,我通常不会用属性枚举所有属性;您通常希望使用特定的属性,因此您只需直接调用 如果您要查找任何属性的属性,请枚举那些基于 GetCustomAttribute 查找属性的属性() 你这样做的方式就是最好的方式。GetCustomAttribute
。
关于c# - 访问属性的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12274246/