c# - 访问属性的最佳方式

标签 c# .net reflection attributes annotations

我正在开发一个使用某些属性标记的框架。这将在 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.GetCustomAttributePropertyInfo/MemberInfo.GetCustomAttribute 是获取属性对象的推荐方式。

虽然,我通常不会用属性枚举所有属性;您通常希望使用特定的属性,因此您只需直接调用 GetCustomAttribute如果您要查找任何属性的属性,请枚举那些基于 GetCustomAttribute 查找属性的属性() 你这样做的方式就是最好的方式。

关于c# - 访问属性的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12274246/

相关文章:

c# - 如何将对象转换为 Type?

.net - 配置 TeamCity MSBuild 和 MSDeploy

javascript - Ajax 调用网页方法不起作用

c# - string.IsNullOrEmpty() 似乎不适用于类中类中的字符串

c# - 使用 C# 反射将可变大小的集合分配给类属性

ruby - 有没有一种优雅的方法来测试一个实例方法是否是另一个实例方法的别名?

c# - 理解 DDD 上下文中的命令模式

c# - WPF 始终在最前面

c# - 如何匹配要插入到 C# 中的 ComboBox 中的数据

java - 如果转换为其实现的接口(interface),则获取原始类